Miguel
Miguel

Reputation: 3496

Highlight text in TextBox/Label/RichTextBox using C#

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.

Upvotes: 3

Views: 6128

Answers (2)

bradenb
bradenb

Reputation: 793

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);

Upvotes: 5

Kevin Stricker
Kevin Stricker

Reputation: 17388

Using a RichTextBox it would be approximately:

textbox.Text = "This is a test.";
textbox.Select(10, 4);
textbox.SelectionFont = new Font(textBox.SelectionFont, FontStyle.Italic);

This isn't possible on a single label, though you could use two.

I'm not completely sure Style is writeable now that I think about it.

Edit: Fixed.

Upvotes: 0

Related Questions