99

I have a text box with a displayed string already in it. To bring the cursor to the textbox I am already doing

txtbox.Focus();

But how do I get the cursor at the end of the string in the textbox ?

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
Anoushka Seechurn
  • 2,166
  • 7
  • 35
  • 52

4 Answers4

166

For Windows Forms you can control cursor position (and selection) with txtbox.SelectionStart and txtbox.SelectionLength properties. If you want to set caret to end try this:

txtbox.SelectionStart = txtbox.Text.Length;
txtbox.SelectionLength = 0;

For WPF see this question.

Marcello B.
  • 4,177
  • 11
  • 45
  • 65
Panu Oksala
  • 3,245
  • 1
  • 18
  • 28
80

There are multiple options:

txtBox.Focus();
txtBox.SelectionStart = txtBox.Text.Length;

OR

txtBox.Focus();
txtBox.CaretIndex = txtBox.Text.Length;

OR

txtBox.Focus();
txtBox.Select(txtBox.Text.Length, 0);
Vishal Suthar
  • 17,013
  • 3
  • 59
  • 105
12

You can set the caret position using TextBox.CaretIndex. If the only thing you need is to set the cursor at the end, you can simply pass the string's length, eg:

txtBox.CaretIndex=txtBox.Text.Length;

You need to set the caret index at the length, not length-1, because this would put the caret before the last character.

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
1

Try like below... it will help you...

Some time in Window Form Focus() doesn't work correctly. So better you can use Select() to focus the textbox.

txtbox.Select(); // to Set Focus
txtbox.Select(txtbox.Text.Length, 0); //to set cursor at the end of textbox
Vishal Suthar
  • 17,013
  • 3
  • 59
  • 105
Pandian
  • 8,848
  • 2
  • 23
  • 33
  • The OP asks about the cursor position, not the selection – Panagiotis Kanavos Dec 06 '13 at 12:04
  • 2
    @PanagiotisKanavos: Can you read my post correctly before comment... – Pandian Dec 06 '13 at 12:05
  • From the docs [TextBox.Select Method](http://msdn.microsoft.com/en-us/library/system.windows.controls.textbox.select(v=vs.110).aspx): **Selects a range of text in the text box.** While you can emulate positioning by manipulating the selection, it's better to just place the cursor where you want it – Panagiotis Kanavos Dec 06 '13 at 12:10