Janet
Janet

Reputation: 1411

Set the background color only for a part of a label asp.net

I am adding labels dynamically to a page, there are a few labels that have to be marked as required . Below is the code

 Panel1.Controls.Add(new LiteralControl("<td>"));
        if (required)
        {
            Mynewlabel.Text = lblname + " *";
            Mynewlabel.BackColor = System.Drawing.Color.Red;
        }
        ControlsPanel.Controls.Add(Mynewlabel);
        ControlsPanel.Controls.Add(new LiteralControl("</td>"));

Setting Mynewlabel.BackColor makes the complete label back color as red , rather I just want the * sign to be in Red ...I am not sure if it is do-able.

Please provide your inputs.

Upvotes: 1

Views: 5288

Answers (4)

IrishChieftain
IrishChieftain

Reputation: 15253

Put the asterisk (*) in its own span tag and apply color to that via CSS class.

A more elegant way would be to inherit your own custom label from Label and apply the CSS rule as a property to that. This way you could have a collection of these on a page without the mess in your code-behind :)

Upvotes: 0

rick schott
rick schott

Reputation: 21117

CSS:

.required
{
   color:red;
}

Code:

Panel1.Controls.Add(new LiteralControl("<td>"));
if (required)
{
    Mynewlabel.Text = lblname;
    Label lblRequired = new Label();
    lblRequired.Text = "*";
    lblRequired.CssClass= "required";
}
ControlsPanel.Controls.Add(Mynewlabel);
ControlsPanel.Controls.Add(lblRequired);
ControlsPanel.Controls.Add(new LiteralControl("</td>"));

Upvotes: 2

Icarus
Icarus

Reputation: 63966

It's doable, but it's ugly:

Mynewlabel.Text = lblname + @"<span style=""color:red;""> *</span>";

Upvotes: 0

Abe Miessler
Abe Miessler

Reputation: 85056

I believe you could do something like this:

Mynewlabel.Text = lblname + @" <span style=""background-color:red"">*</span>";

Which seems a little crufty but if you want the styling you descirbed in the context of one label this might be your only option.

Upvotes: 0

Related Questions