In .NET, you can easily get the line number of the cursor location of a TextBox
(i.e. the "current line") by using GetLineFromCharIndex
and SelectionStart
:
var currentLine = textBox1.GetLineFromCharIndex(textBox1.SelectionStart);
Is there a "clean/native" way to set the cursor in a given line of a Textbox
(i.e. set the "current line")? Or at least a "clean/native" way to get the char index of the first character of a given line (something like getCharIndexFromLine
, the opposite of the function I put before)?
A way to do it would involve iterating over the first N-1
elements of the Lines
property of the TextBox
and summing their lengths plus the lengths of the linebreaks. Any other idea?
There is a GetFirstCharIndexFromLine()
function that is available:
int myLine = 3;
int pos = textBox1.GetFirstCharIndexFromLine(myLine);
if (pos > -1) {
textBox1.Select(pos, 0);
}
This was the best I could come up with:
private void SetCursorLine(TextBox textBox, int line)
{
int seed = 0, pos = -1;
line -= 1;
if(line == 0) pos = 0;
else
for (int i = 0; i < line; i++)
{
pos = textBox.Text.IndexOf(Environment.NewLine, seed) + 2;
seed = pos;
}
if(pos != -1) textBox.Select(pos, 0);
}
If you want to start counting lines at 0 remove the line -= 1;
segment.
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