Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 502
Joan Venge Avatar asked Oct 12 '22 01:10

Joan Venge


1 Answers

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

like image 107
SwDevMan81 Avatar answered Oct 15 '22 10:10

SwDevMan81