问题
How can I scroll to a specified line number of a RichTextBox control using C#? It's the WinForms version.
回答1:
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.
回答2:
With this code the cursor jumps to the first column in the wanted line.
It works perfectly in any case.
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();
}
回答3:
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()
?
回答4:
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.
来源:https://stackoverflow.com/questions/4323105/how-can-i-scroll-to-a-specified-line-number-of-a-richtextbox-control-using-c