Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move the textbox caret to the right

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;
}
like image 921
monkey_boys Avatar asked Jul 24 '09 14:07

monkey_boys


People also ask

How to change cursor position in TextBox?

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.

What is a caret in TextBox?

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.

How can set cursor position in TextBox in asp net?

Try to put the textBox1. Focus() method at the end of button_Click method code, that will place the cursor into the textBox1.


2 Answers

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;
like image 78
Fredrik Mörk Avatar answered Oct 16 '22 14:10

Fredrik Mörk


            tbNumber.SelectionStart = tbNumber.Text.ToCharArray().Length;
            tbNumber.SelectionLength = 0;
like image 41
jdc Avatar answered Oct 16 '22 13:10

jdc