KeyPress Event

S

Scott

I have the snippet of code at the end of this message that has the following
line of code in it:
txtYourFirstname.SelectedText=Convert.ToString(Char.ToUpper(e.KeyChar));
The problem I am having is when it converts lowercase to upper case it also
leaves the lowercase character in the textbox. In other words, if you type
the letter 'q' in the textbox it will convert it to uppercase but show 'Qq'.
What am I doing wrong, and how can I correct it? Also, I'm just starting to
learn C#.


private void txtYourFirstname_KeyPress(object sender,
System.Windows.Forms.KeyPressEventArgs e)
{
//Validate for non-Character values
if(!Char.IsLetter(e.KeyChar) && !Char.IsControl(e.KeyChar))
{
e.Handled = true; //Remove/Prevent values from being entered if
non-Character
}
else
{
txtYourFirstname.SelectedText=Convert.ToString(Char.ToUpper(e.KeyChar));
}
}
 
P

Paul E Collins

You are setting TextBox.SelectedText rather than TextBox.Text.

If you just want to force all input to be upper-case, you can use the
CharacterCasing property of the TextBox.

P.
 
S

Scott

Thanks Paul. The CharacterCasting property worked.

I did try textbox.text, but it did the samething as the textbox.Selectedtext
did. I choose the Selectedtext property over the text property because it
put the cursor at the end of the line. The text property for some reason
put it at the begining.
 
P

Paul E Collins

- Setting Text replaces the entire contents of the TextBox.
- Setting SelectedText replaces only the user's highlighted selection.

Since there was no highlighted selection in the box, setting SelectedText
will *insert* the text at the cursor position.

By the way, you can use that "KeyPressEventArgs e". If you set e.Handled =
true, the keystroke will be considered to have been processed, and the
result of pressing that key won't automatically appear in the textbox.

P.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top