1

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!

greg
  • 1,289
  • 2
  • 14
  • 33
angfreak
  • 993
  • 2
  • 11
  • 27

4 Answers4

5

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

Community
  • 1
  • 1
Niranjan Singh
  • 18,017
  • 2
  • 42
  • 75
  • It is okay. But when i click on any item (menu in my user control), it seems that it rebind, actually a flickering occur , how can i avoid this?? – angfreak May 17 '13 at 10:01
  • 1
    this flicker causes by the postback that happens every time you click the links , and this is a normal behaviour in asp.net, note that the website you mentioned using the Ajax technology so thatpartial page updates can achieved ,and the page will be updated without submitting (posting ) the whole page . [ref](http://forums.asp.net/t/1160202.aspx/1) – Niranjan Singh May 17 '13 at 10:05
0

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);          
//}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
0

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);
Rahul
  • 5,603
  • 6
  • 34
  • 57
0

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

tariq
  • 2,193
  • 15
  • 26