Q:

How to modify current line in multicolored richtextbox in C#

I have a multicolored richtextbox control in winforms, as shown

I need to modify the value in the last line (here 3 in "Line 3"). I tried it with the following code
int pos = richtextbox.LastIndexOf("3");
richtextbox.Text = richtextbox.Text.Substring(0,pos) + "4";

The value 3 is successfully changed to 4 but the colors of lines are not preserved. They all get colored the same as that of the first line, as shown.

How can I change a value without changing the colors.

A:

This works for me:
// GET LAST LINE
string LastLineText = richTextBox1.Lines[richTextBox1.Lines.Count() - 1];
int LastLineStartIndex = richTextBox1.Text.LastIndexOf(LastLineText);

// SELECT TEXT
richTextBox1.SelectionStart = LastLineStartIndex;
richTextBox1.SelectionLength = LastLineText.Length;

// REPLACE TEXT
richTextBox1.SelectedText = "Line 4";

