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 ?
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 ?
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.
Math.max(0, txtbox.Text.Length -1); // Math.max is the logic if length is 0
–
Columbarium -1
puts the insertion point before the last character (her|e
) instead of after it (here|
). Also, text boxes have a .TextLength
property so all you need is txtBox.SelectionStart = txtbox.TextLength
. –
Indispose 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);
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.
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
© 2022 - 2024 — McMap. All rights reserved.