C # - RichTextBox changes the color of certain words

Possible duplicate:
How to select text from RichTextBox and then its color?

I do not have any code to display, because I do not know :( I have a server that displays information with tags. For example:

15:44 [INFO] Loaded Properties
15:45 [ERROR] Properties not found

How can I look in richtextbox and make ERROR tags red, INFO GREEN tags, etc.?

+5
source share
2 answers

I think this should do what you want:

for(int i=0; i<rtb.Lines.Length; i++) 
{ 
   string text = rtb.Lines[i];
   rtb.Select(rtb.GetFirstCharIndexFromLine(i), text.Length); 
   rtb.SelectionColor = colorForLine(text); 
} 

private Color colorForLine(string line)
{
    if(line.Contains("[INFO]", StringComparison.InvariantCultureIgnoreCase) return Color.Green;
    if(line.Contains("[ERROR]", StringComparison.InvariantCultureIgnoreCase) return Color.Red;

    return Color.Black;
}

Edit: Changed StartsWithtoContains

+2
source

You can do something like:

//will select characters form index 0 to 9
richTextBox1.Select(0, 10);

//will set the characters from 0 to 9 to red
richTextBox1.SelectionColor = Color.Red; 
0
source

All Articles