Tony_Henrich
Tony_Henrich

Reputation: 44105

How to place a declared panel in a declared placeholder in code behind?

I have an aspx page with different placeholders and different asp panels declared in the page. In certain conditions I would like to display certain panels inside certain placeholders. I know how to do this in Javascript and I know how to add a programatically created control in a placeholder's controls collection. However my panels and placeholders are already declared in the page.

I was wondering if there's a way to put an already declared panel in a placeholder in code behind?

Upvotes: 0

Views: 574

Answers (2)

JAKEtheJAB
JAKEtheJAB

Reputation: 289

Since the ASP.NET control hierarchy is built very early on in the page life cycle, in order to dynamically add panel controls to placeholder controls, you will have to do that in the during the Page_Init event1.

protected override void OnInit(EventArgs e)
{
    base.OnInit(e);

    Panel pnl = new Panel();

    plc.Controls.Add(pnl);
}

Upvotes: 0

Win
Win

Reputation: 62260

However my panels and placeholders are already declared in the page.

Yes, you can relocate Panel1 located inside PlaceHolder1 to PlaceHolder2. However, it is not common to relocate controls which are already declared in aspx page.

<asp:PlaceHolder runat="server" ID="PlaceHolder1">
    <asp:Panel runat="server" ID="Panel1">
        <h1>Panel 1</h1>
    </asp:Panel>
</asp:PlaceHolder>
<asp:PlaceHolder runat="server" ID="PlaceHolder2">
    <asp:Panel runat="server" ID="Panel2">
        <h1>Panel 2</h1>
    </asp:Panel>
</asp:PlaceHolder>

PlaceHolder1.Controls.Add(Panel2);
PlaceHolder2.Controls.Add(Panel1);

There are following alternative method you might want to consider -

Method 1

Show and hide panels based on your logic. For example, SomePanel.Visible = true|false;

Note: Ideally, you do not want to add a lot of controls to a page; the reason is ViewState will be very heavy even if they are not displayed to a user.

However, it is very easy to implement compare to other methods.

Method 2

Load UserControl to PlaceHolder dynamically.

var control = LoadControl("SomeUserControl.ascx");
YourPlaceholder.Controls.Add(control);

Method 3

Create controls dynamically. It is a lot more complicated, because you need to reload those controls on every post back.

Upvotes: 2

Related Questions