Ankur Choudhari
Ankur Choudhari

Reputation: 31

How to set different forecolor to single label?

lblOperationType.Text = "Text";
Label l1 = new Label();
int len = lblOperationType.Text.Length - 1;
string b = Convert.ToString(lblOperationType.Text.ToCharArray()[0]);
string a = lblOperationType.Text.Substring(1, len);
l1.Text = (b);
l1.ForeColor = Color.Red;
lblOperationType.Text = l1.Text + a;

Is this correct code? I have to make a single label Text like 1st Letter should be red in color.

Upvotes: 2

Views: 1206

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1504162

No, in general (i.e. without custom rendering yourself) a label only has a single foreground colour. Assuming this is Windows Forms, it sounds like you might want a RichTextBox instead - that allows multiple colours, fonts etc within a single control.

As an example:

using System;
using System.Drawing;
using System.Windows.Forms;

class Test
{
    static void Main()
    {
        var rtb = new RichTextBox {
            Text = "Test",
            ReadOnly = true
        };
        rtb.Select(1, 3);
        rtb.SelectionColor = Color.Red;
        rtb.DeselectAll();
        var form = new Form { Controls = { rtb } };
        Application.Run(form);
    }
}

That's not terribly nice code - it would be better to set the Rtf property directly, with the control codes necessary to set the colour, but I'm having a tricky time getting the exact format of the RTF right.

Upvotes: 3

Related Questions