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

 ̄綄美尐妖づ 提交于 2019-12-02 01:09:44

问题


how can I update just one line text in richtextbox?

String[] lines = richTextBox8.Lines;
lines[2] += " ";
richTextBox8.Lines = lines;

I am using this code part for update second line of richtextbox but it scans all my richtextbox lines and it takes many times.

so I want to update line text for 1 line.

How can I do that?


回答1:


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] + " ");


来源:https://stackoverflow.com/questions/29445411/c-sharp-how-can-i-update-just-one-line-text-in-richtextbox

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