tags:

views:

1473

answers:

2

Hello!!

How can I scroll to a specified line in a WinForms TextBox using C#?

Thanks

+12  A: 

Here's how you scroll to the selection:

textBox.ScrollToCaret();

To scroll to a specified line, you could loop through the TextBox.Lines property, total their lengths to find the start of the specified line and then set TextBox.SelectionStart to position the caret.

Something along the lines of this (untested code):

int position = 0;

for (int i = 0; i < lineToGoto; i++)
{
    position += textBox.Lines[i].Length;
}

textBox.SelectionStart = position;

textBox.ScrollToCaret();
dommer
+1 for understanding the question :)
SirDemon
i thank you for your answer...
alinpopescu
A: 

The looping answer to find the proper caret position has a couple of problems. First, for large text boxes, it's slow. Second, tab characters seem to confuse it. A more direct route is to use the text on the line that you want.

String textIWantShown = "Something on this line.";
int position = textBox.Text.IndexOf(textIWantShown);
textBox.SelectionStart = position;
textBox.ScrollToCaret();

This text must be unique, of course, but you can obtain it from the textBox.Lines array. In my case, I had prepended line numbers to the text I was displaying, so this made life easier.