Format text in a RichTextBox in C#

[RichTextBox]

To format text in a RichTextBox, use the control’s Select method to select the text. Then use the “Selection” properties (SelectionAlignment, SelectionBackColor, SelectionFont, etc.) to set the properties for the selected text.

This example uses the following code to format three pieces of text in the first RichTextBox.

// Format RichTextBox1.
richTextBox1.Select(4, 5);
richTextBox1.SelectionColor = Color.Red;
richTextBox1.Select(16, 3);
richTextBox1.SelectionFont =
    new Font(richTextBox1.Font, FontStyle.Italic);
richTextBox1.Select(35, 4);
richTextBox1.SelectionBackColor = Color.Yellow;
richTextBox1.SelectionColor = Color.Brown;
richTextBox1.Select(0, 0);

To make formatting a little easier, the following SelectRichText method selects a target string within a RichTextBox.

// Select the indicated text.
private void SelectRichText(RichTextBox rch, string target)
{
    int pos = rch.Text.IndexOf(target);
    if (pos < 0)
    {
        // Not found. Select nothing.
        rch.Select(0, 0);
    }
    else
    {
        // Found the text. Select it.
        rch.Select(pos, target.Length);
    }
}

The program uses this method to format text in its second RichTextBox as shown in the following code.

SelectRichText(richTextBox2, "quick");
richTextBox2.SelectionColor = Color.Red;


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in controls and tagged , , , , , , , , , , , . Bookmark the permalink.

2 Responses to Format text in a RichTextBox in C#

  1. jean says:

    hey thanks for this post, i just have a question : how to do the same using MVVM ??? thx a lot

    • RodStephens says:

      You could provide tools to set the selected text’s font properties: bold, italic, font name, font size, color, etc.

      In that case, you could store the text as RTF text in a string. That would be your model. The RichTextBox would be a view and a controller. You could also have a read-only RichTextBox that acts as a view only.

      Does that help? Or did you have something more specific in mind?

Leave a Reply

Your email address will not be published. Required fields are marked *