简体   繁体   English

从后台代码添加时,在父标签控件的标签之间添加asp.net标签

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

I am adding a parent asp.net label to my page in the code-behind like this: 我在代码中将父asp.net标签添加到页面中,如下所示:

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: 我需要最终输出看起来像我在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? 如何从上面的代码后面的中间添加所需的标签?

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. 外部Label的Text属性是使用Literal控件设置的,否则当内部Label添加到Controls集合时,文本将被覆盖。 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控件,但“ Testing”将不会显示在外部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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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