Mr. Smith
Mr. Smith

Reputation: 5558

How can I scroll to a specified line number of a RichTextBox control using C#?

How can I scroll to a specified line number of a RichTextBox control using C#? It's the WinForms version.

Upvotes: 7

Views: 10934

Answers (4)

marsh-wiggle
marsh-wiggle

Reputation: 2803

With this code the cursor jumps to the first column in the wanted line.

It works perfectly in any case, even when the wanted line occurs several times.

void GotoLine(int wantedLine_zero_based) // int wantedLine_zero_based = wanted line number; 1st line = 0
{
    int index = this.RichTextbox.GetFirstCharIndexFromLine(wantedLine_zero_based);
    this.RichTextbox.Select(index, 0);
    this.RichTextbox.ScrollToCaret();
}

Upvotes: 7

TeenMrDragon
TeenMrDragon

Reputation: 1

Would it help in this situation to split up the text? For example:

string[] lines = myRichTextBox.Text.Split('\n');
int linesCount = lines.Length;

This will tell you the number of lines.

Upvotes: -2

jvanrhyn
jvanrhyn

Reputation: 2824

You can try something like this.

    void ScrollToLine(int lineNumber)
    {
        if (lineNumber > richTextBox1.Lines.Count()) return;

        richTextBox1.SelectionStart = richTextBox1.Find(richTextBox1.Lines[lineNumber]);
        richTextBox1.ScrollToCaret();
    }

This will not work perfectly if you have lots of repetition within your RichTextBox. I do hope that it might be of some use to you.

Upvotes: 13

Turrau
Turrau

Reputation: 452

I'm not sure, if it has a method for this, but how about counting the linebreaks in the Text and then set the caret (via SelectionStart and SelectionLength) and ScrollToCaret()?

Upvotes: 1

Related Questions