Yasser Mohseni
Yasser Mohseni

Reputation: 463

RichTextBox different back color for each line

I am developing a windows form application using C#.Net. In part of my code I defined a function to log system events. Here is the body of this function:

richTextBoxLog.Text += "-";
richTextBoxLog.Text += some logs and strings ...;
richTextBoxLog.Text += "." + new string(' ', 1000) + Environment.NewLine;
richTextBoxLog.Select(richTextBoxLog.GetFirstCharIndexFromLine(logCounter), richTextBoxLog.Lines[logCounter].Length);       
richTextBoxLog.SelectionBackColor = (logCounter % 2 == 0) ? Color.LightBlue: Color.LightGray;
logCounter++;
richTextBoxLog.ScrollToCaret();

the initial value of logCounter is zero (the line of first event refers to logCounter=0). For odd lines the back color should be Color.LightGray and for even lines it should be Color.LightBlue. However as you can see below it does not change the back color properly.

First Event (Even color) Second Event (Odd color) Third Event (Even color) Fourth Event (Odd color) Fifth Event (Even color)

Each time this function is called (to add new text line) the region of richTextBoxLog.Select is updated according to the new line's start and end indices. But when an even line is added to the text box the back color of all of the previous lines turn into blue (even color).

I appreciate your help in advance.

Upvotes: 0

Views: 10923

Answers (2)

R.T.E.
R.T.E.

Reputation: 1

It should be Helpfull:

    public  void AppendText(string text, Color color,Color backColor)
    {
        richTextBox1.SelectionStart = richTextBox1.TextLength;
        richTextBox1.SelectionLength = 0;
        richTextBox1.SelectionColor = color;
        richTextBox1.AppendText(text);
        richTextBox1.SelectionColor = richTextBox1.ForeColor;
        richTextBox1.SelectionBackColor = backColor;
        richTextBox1.ScrollToCaret();
    }

Upvotes: 0

Rassi
Rassi

Reputation: 1622

Documentation http://msdn.microsoft.com/en-us/library/system.windows.forms.richtextbox.selectionbackcolor.aspx states:

Characters that are entered from that position have the specified SelectionBackColor.

Which seems likely to cause your issues. Although I still can't see how it influences previously added text.

Anyways, you can solve it by repainting all line colors when you add text:

richTextBoxLog.Text += "-";
richTextBoxLog.Text += some logs and strings ...;
richTextBoxLog.Text += "." + new string(' ', 1000) + Environment.NewLine;
var lineCount = 0;
foreach (var line in richTextBoxLog.Lines) {
  richTextBoxLog.Select(richTextBoxLog.GetFirstCharIndexFromLine(lineCount), line.Length);
  richTextBoxLog.SelectionBackColor = (lineCount % 2 == 0) ? Color.LightBlue : Color.LightGray;
  lineCount++;
}
richTextBoxLog.ScrollToCaret();

Upvotes: 3

Related Questions