简体   繁体   中英

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.

No, in general (ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM