1

I have a multicolored richtextbox control in winforms, as shown

enter image description here

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.

enter image description here

How can I change a value without changing the colors.

Yannick Meeus
  • 5,643
  • 1
  • 35
  • 34
Aneesh Relan
  • 342
  • 3
  • 12

1 Answers1

0

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";
Equalsk
  • 7,954
  • 2
  • 41
  • 67