将单个控件添加到多个占位符

时间:2014-08-10 07:43:43

标签: asp.net-placeholder

我的page.aspx中有两个占位符:

<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>

// Other tags

<asp:PlaceHolder ID="PlaceHolder2" runat="server"></asp:PlaceHolder>

我在page.aspx.cs中创建了一个HtmlGenericControl,并想在PlaceHolders中添加它:

HtmlGenericControl NewControl = new HtmlGenericControl("div");
NewControl.ID = "newDIV";
NewControl.Attributes.Add("class", "myClass");
NewControl.InnerHtml = "**myContent**";
PlaceHolder1.Controls.Add(NewControl);
PlaceHolder2.Controls.Add(NewControl);

问题是只有最后添加才会生效!

The Line

PlaceHolder1.Controls.Add(NewControl);

不起作用!

我错了吗?

提前致谢。

1 个答案:

答案 0 :(得分:1)

控件不能是超过1个父控件的子控件。您必须创建两次HtmlGenericControl:

Func<HtmlGenericControl> createControl = () => {
    HtmlGenericControl newControl = new HtmlGenericControl("div");
    newControl.ID = "newDIV";
    newControl.Attributes.Add("class", "myClass");
    newControl.InnerHtml = "**myContent**";
    return newControl;
};

PlaceHolder1.Controls.Add( createControl() );
PlaceHolder2.Controls.Add( createControl() );