Highlight text in TextBox/Label/RichTextBox using C#

c#

Solution

RichTextBox r = new RichTextBox();
r.Text = "This is a test";
r.Select(r.Text.IndexOf("test"), "test".Length);
r.SelectionFont = new Font(r.Font, FontStyle.Italic);
r.SelectionStart = r.Text.Length;
r.SelectionLength = 0;

Something to that effect will work and remove the selection.

EDIT It should be relatively easy to encapsulate in your own method. You could even make an extension:

public static class Extensions
{
    public static void StyleText(this RichTextBox me, string text, FontStyle style)
    {
        int curPos = me.SelectionStart;
        int selectLen = me.SelectionLength;
        int len = text.Length;
        int i = me.Text.IndexOf(text);

        while (i >= 0)
        {
            me.Select(i, len);
            me.SelectionFont = new Font(me.SelectionFont, style);
            i = me.Text.IndexOf(text, i + len);
        }

        me.SelectionStart = curPos;
        me.SelectionLength = selectLen;
    }
}

and then use it like:

richTextBox1.Text = "This is a test";
richTextBox1.StyleText("test", FontStyle.Italic);

Problem

Good night, I would like to know how can I highlight a part of the text contained in a TextBox, Label (preferably) or RichTextBox. For example, given the string "This is a test.", I would like the control to show "This is a test.". Is there any easy way I can do it? Thank you very much.

Original source