1

我有一个 home.aspx 页面,其中有两个面板。在第一个面板中,我动态绑定了一个用户控件(用于在左侧显示 meiny),在第二个面板中,我显示了页面。我在页面加载时动态绑定用户控件。

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

    }

当页面第一次加载时我usercontrol是绑定并显示我的菜单,但是当我点击它隐藏的任何菜单项(用户控件)时,

请帮助我,在此先感谢!

4

4 回答 4

5

将这行代码放在Page生命周期的Page_Init事件上。

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

正确的方式:

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 (!IsPostBack)在回发后使用 then ,它将不会被添加到页面中。第一次您将能够在页面上看到控件。

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

于 2013-05-17T09:50:06.917 回答
0

这是一个动态控件,必须在每次回发时重新创建并读取到页面中。

所以这将起作用:

//if (!IsPostBack)
//{
    UserControl uc = (UserControl)Page.LoadControl("~/settings/Links/Navigation.ascx");
    Accordion1.Controls.Add(uc);          
//}
于 2013-05-17T09:49:57.510 回答
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);
于 2013-05-17T09:52:17.050 回答
0

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

于 2013-05-17T09:55:07.343 回答