el ninho
el ninho

Reputation: 4233

Dynamically changing properties of Label text

I have text with "wild characters", like "@ARed text" where @A is sign for red colour. I need to replace @A with some function (or something like that) so wherever there is @A in text, text font becomes red coloured. I have several colours (@B, @C...) so for every of them I need to do same thing, just different colour.

So, "@ASome red text @BSome green text" would be coloured red and green respectively (can't find text colouring here on SO).

Any ideas?

Thanks.

Upvotes: 1

Views: 1181

Answers (1)

user596075
user596075

Reputation:

What I would do is capture the PreRender event of the label and test for YourLabel.Text.Substring(0, 1) and if that is the at-sign (@) then conditionally test (I'd use a switch) the second character. You can then get the rest of the string without the @A and set the Label's text then, and format according to the property characters.

Something like this:

protected void YourLabel_PreRender(object sender, EventArgs e)
{
    string LabelText = YourLabel.Text;
    bool NewForeColor = false;

    if (LabelText.Left(0, 1) == "@")
    {
        switch(LabelText.Substring(1, 1))
        {
            case "A":
                YourLabel.ForeColor = System.Drawing.Color.Magenta;
                NewForeColor = true;
                break;
            case "B":
                // you get the idea
                break;
        }
        if (NewForeColor)
            YourLabel.Text = LabelText.Substring(2, LabelText.Length - 2);
    }
}

Edit: this is untested code, but you should get the general idea of the logic.

Upvotes: 2

Related Questions