Adding an asp.net label in between the tags of a parent label control when adding from the code-behind

468 Views Asked by At

I am adding a parent asp.net label to my page in the code-behind like this:

Label lbl = new Label();
lbl.ID = "lblPrimary";
lbl.Text = "Testing";
placeholder.Controls.Add(lbl);

I need the end output to look as if I did the following in the aspx:

<asp:Label ID="lblPrimary" runat="server" Text="Testing">
     <asp:Label runat="server" SkinID="Required"></asp:Label>
</asp:Label>

How can I add the required label in between from the code-behind like above?

1

There are 1 best solutions below

0
ConnorsFan On

You can try the following code. The Text property of the outer Label is set with a Literal control, otherwise the text is overwritten when the inner Label is added to the Controls collection. If you want the exact result specified in your question, you can forget the Literal control but "Testing" will not be displayed in the outer Label.

Literal literalInner = new Literal();
literalInner.Text = "Testing";

Label lblInner = new Label();
lblInner.Attributes.Add("SkinID", "Required");

Label lblOuter = new Label();
lblOuter.ID = "lblPrimary";
lblOuter.Controls.Add(literalInner);
lblOuter.Controls.Add(lblInner);

placeholder.Controls.Add(lblOuter);