Joan Venge
Joan Venge

Reputation: 330872

How to have alternating line colors for a Winforms RichTextBox?

Something that looks like this:

enter image description here

Is there a line-like property where I could do?:

foreach line ...
    line.BackColor = Colors.Gray;

Lines[i] property returns just a string.

Upvotes: 5

Views: 5726

Answers (1)

SwDevMan81
SwDevMan81

Reputation: 49978

A not so great solution would be to append extra text onto each line and then highlight the full text. So something like this:

// Update lines to have extra length past length of window
string[] linez = new string[richTextBox1.Lines.Length];
for (int i = 0; i < richTextBox1.Lines.Length; i++)
{
   linez[i] = richTextBox1.Lines[i] + new string(' ', 1000);
}
richTextBox1.Clear();
richTextBox1.Lines = linez;

for(int i = 0; i < richTextBox1.Lines.Length; i++)
{
   int first = richTextBox1.GetFirstCharIndexFromLine(i);
   richTextBox1.Select(first, richTextBox1.Lines[i].Length);
   richTextBox1.SelectionBackColor = (i % 2 == 0) ? Color.Red : Color.White;
   richTextBox1.SelectionColor = (i % 2 == 0) ? Color.Black : Color.Green;
}
richTextBox1.Select(0,0);

It would look like this:

RichTextBox with colored lines

Upvotes: 6

Related Questions