Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

richtextbox

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?

like image 336
nec Avatar asked Oct 18 '25 15:10

nec


1 Answers

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] + " ");
like image 165
TaW Avatar answered Oct 21 '25 06:10

TaW