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.
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.
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();
}
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()
?
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.
精彩评论