Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RichTextBox color selected lines

I am new to windows Forms. I am using VS 2008, C# to write a RichTextBox. I want to be able to color each line with a different color as I write to the RichTextBox. Can someone point me to samples. Thanks

foreach (string file in myfiles)
{
  // As I process my files
  // richTextBox1.Text += "My processing results";
  if(file == "somefileName")
  {
    // Color above entered line or enter new colored line
  }

}
like image 634
Picflight Avatar asked Feb 23 '09 18:02

Picflight


People also ask

How to change the color of selected text in RichTextBox in c#?

You can manipulate the current selection using the Find method or using SelectionStart and SelectionLength properties. Then you can change properties of selected text using SelectionXXX properties. For example, SelectionColor would set the color of current selection, etc.

When should we use RichTextBox?

A RichTextBox is a better choice when it is necessary for the user to edit formatted text, images, tables, or other rich content. For example, editing a document, article, or blog that requires formatting, images, etc is best accomplished using a RichTextBox.


1 Answers

Set SelectionColor before you append, something like:

    int line = 0;
    foreach (string file in myfiles)
    {
        // Whatever method you want to choose a color, here
        // I'm just alternating between red and blue
        richTextBox1.SelectionColor = 
            line % 2 == 0 ? Color.Red : Color.Blue;

        // AppendText is better than rtb.Text += ...
        richTextBox1.AppendText(file + "\r\n");
        line++;
    }
like image 199
Daniel LeCheminant Avatar answered Oct 03 '22 02:10

Daniel LeCheminant