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

假如想象 提交于 2020-01-03 14:13:51

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!