Why part of the string in the richTextBox is colored in green?

Chocolade 536 Reputation points
2022-04-24T20:22:33.11+00:00
private void ColorRichTextbox(RichTextBox box, string text, Color color, bool appendNewLine = true)  
        {  
            int length = box.TextLength;  
            if (!string.IsNullOrWhiteSpace(box.Text) && appendNewLine)  
            {  
                box.AppendText("\r\n" + text);  
            }  
            else  
            {  
                box.AppendText(text);  
            }  
            box.SelectionStart = length;  
            box.SelectionLength = text.Length;  
            box.SelectionColor = color;  
        }  

Then in button click event the first line in the richTextBox will be light green :

ColorRichTextbox(richTextBoxLogChanges, "Watching Event Started : ", Color.White);  
ColorRichTextbox(richTextBoxLogChanges, DateTime.Now.ToString(), Color.LightGreen, false);  

Then i'm adding another line in yellow :

private void Fsw_Deleted(object sender, FileSystemEventArgs e)  
        {  
            ColorRichTextbox(richTextBoxLogChanges, $"Deleted: {e.FullPath}", Color.Yellow);  
        }  

The yellow line the last char get the light green color of the first line :

In the screenshot in this example the last char S of the css is in light green and it should be in yellow.

195880-line1.jpg

Screenshot of the last problem mentioned in my comment/s to the solution :

195932-watcher1.jpg

Developer technologies | Windows Forms
Developer technologies | C#
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 122.6K Reputation points
    2022-04-24T20:30:51.227+00:00

    Check a possible fix:

    private void ColorRichTextbox(RichTextBox box, string text, Color color, bool appendNewLine = true)
    {
       int length = box.TextLength;
       int sl;
       if (!string.IsNullOrWhiteSpace(box.Text) && appendNewLine)
       {
          box.AppendText("\r\n" + text);
          sl = text.Length + 2;
       }
       else
       {
          box.AppendText(text);
          sl = text.Length;
       }
       box.SelectionStart = length;
       box.SelectionLength = sl;
       box.SelectionColor = color;
    }
    

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.