Setting cursor at the end of any text of a textbox

C#WpfTextboxCursor Position

C# Problem Overview


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 ?

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

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);

Solution 3 - C#

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.

Solution 4 - C#

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnoushka SeechurnView Question on Stackoverflow
Solution 1 - C#Panu OksalaView Answer on Stackoverflow
Solution 2 - C#Vishal SutharView Answer on Stackoverflow
Solution 3 - C#Panagiotis KanavosView Answer on Stackoverflow
Solution 4 - C#PandianView Answer on Stackoverflow