Search code examples
asp.net-placeholder

Add a single control to multiple placeholders


There are two placeholders in my page.aspx:

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

// Other tags

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

I've created one HtmlGenericControl in page.aspx.cs and want to add it in both 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 problem is that just the last Add takes effect !

The Line

PlaceHolder1.Controls.Add(NewControl);

does not work !

Am I wrong ?

Thanks in advance.


Solution

  • A control cannot be a child of more than 1 parent control. You must create your HtmlGenericControl twice:

    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() );