I would like to change all the characters entered into a textbox to upper case. The code will add the character, but how do I move the caret to the right?
private void textBox3_KeyPress(object sender, KeyPressEventArgs e)
{
textBox3.Text += e.KeyChar.ToString().ToUpper();
e.Handled = true;
}
To position the cursor at the end of the contents of a TextBox control, call the Select method and specify the selection start position equal to the length of the text content, and a selection length of 0.
A caret (sometimes called a "text cursor") is an indicator displayed on the screen to indicate where text input will be inserted. Most user interfaces represent the caret using a thin vertical line or a character-sized box that flashes, but this can vary. This point in the text is called the insertion point.
Try to put the textBox1. Focus() method at the end of button_Click method code, that will place the cursor into the textBox1.
Set the CharacterCasing
property of the TextBox
to Upper
; then you don't need to process it manually.
Note that textBox3.Text += e.KeyChar.ToString().ToUpper();
will append the new character to the end of the string even if the input caret is in the middle of the string (which most users will find highly confusing). For the same reason we cannot assume that the input caret should appear at the end of the string after inputting the character.
If you would still really want to do this in code, something like this should work:
// needed for backspace and such to work
if (char.IsControl(e.KeyChar))
{
return;
}
int selStart = textBox3.SelectionStart;
string before = textBox3.Text.Substring(0, selStart);
string after = textBox3.Text.Substring(before.Length);
textBox3.Text = string.Concat(before, e.KeyChar.ToString().ToUpper(), after);
textBox3.SelectionStart = before.Length + 1;
e.Handled = true;
tbNumber.SelectionStart = tbNumber.Text.ToCharArray().Length;
tbNumber.SelectionLength = 0;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With