c# how can I update just one line text in richtextbox?

蓝咒 提交于 2019-12-01 21:50:50

Note that you must never touch the Text or the Lines directly or all previous formatting gets messed up.

Here is a function that will solve the problem without messing up the formatting:

void changeLine(RichTextBox RTB, int line, string text)
{
    int s1 = RTB.GetFirstCharIndexFromLine(line);
    int s2 = line < RTB.Lines.Count() - 1 ?
              RTB.GetFirstCharIndexFromLine(line+1) - 1 : 
              RTB.Text.Length;        
    RTB.Select(s1, s2 - s1);
    RTB.SelectedText = text;
}

Note the in C# the numbering is zero beased, so to change the 1st line you call changeLine(yourrichTextBox, 0, yourNewText);

To only modify (not replace) the line you can simply access the Lines property; just make sure never to change it!

So to add a blank to the 2nd line you can write:

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