Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting the cursor's current line on a .NET TextBox

Tags:

c#

.net

vb.net

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?

like image 247
Racso Avatar asked Jul 21 '13 06:07

Racso


2 Answers

There is a GetFirstCharIndexFromLine() function that is available:

int myLine = 3;
int pos = textBox1.GetFirstCharIndexFromLine(myLine);
if (pos > -1) {
  textBox1.Select(pos, 0);
}
like image 197
LarsTech Avatar answered Nov 17 '22 12:11

LarsTech


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.

like image 42
Romano Zumbé Avatar answered Nov 17 '22 10:11

Romano Zumbé