angfreak
angfreak

Reputation: 1003

User control not displayed after postback

I have a home.aspx page, where i have two panel. In first panel I have dynamically bound a User Control (for displaying meiny at left side) and in second I have displayed pages. I bound user control dynamically at page load like.

if (!IsPostBack)
    {
        UserControl uc = (UserControl)Page.LoadControl("~/settings/Links/Navigation.ascx");
        Accordion1.Controls.Add(uc);          

    }

when page first time loaded my usercontrol is bind and my menus are displayed, but when I clicked on any menu item it hides(user control),

Please help me, thanks in advance!

Upvotes: 1

Views: 4921

Answers (4)

Niranjan Singh
Niranjan Singh

Reputation: 18260

Put this line of code on Page_Init event of Page life cycle.

UserControl uc = (UserControl)Page.LoadControl("~/settings/Links/Navigation.ascx");
Accordion1.Controls.Add(uc);    

Proper way:

protected void Page_Init(object sender, EventArgs e)
{

      //MyControl is the Custom User Control with a code behind file
      MyControl myControl = (MyControl)Page.LoadControl("~/MyControl.ascx");

      //UserControlHolder is a place holder on the aspx page where I want to load the
      //user control to.
      UserControlHolder.Controls.Add(myControl);

}

If you use if (!IsPostBack) then after postback it will not be added to the page. At the first time you will be able to see the control on the page.

Reference:
ASP.NET Custom user control to add dynamically
How to: Create Instances of ASP.NET User Controls Programmatically

Upvotes: 5

tariq
tariq

Reputation: 2258

It must be loaded on each postback. keep the user control loading code outside if(!IsPostBack){}.

Upvotes: 0

Rahul
Rahul

Reputation: 5636

For Dynamic control there is no need for !IsPostBack Property of page, Remove this property and use

UserControl uc = (UserControl)Page.LoadControl("~/settings/Links/Navigation.ascx");
Accordion1.Controls.Add(uc);

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460340

It's a dynamic control which must be recreated and readded to the page on every postback.

So this will work:

//if (!IsPostBack)
//{
    UserControl uc = (UserControl)Page.LoadControl("~/settings/Links/Navigation.ascx");
    Accordion1.Controls.Add(uc);          
//}

Upvotes: 0

Related Questions