c# - 回发后不显示用户控件

标签 c# asp.net user-controls

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

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

    }

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

请帮助我,在此先感谢!

最佳答案

把这行代码放在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),那么在回发之后它不会被添加到页面中。第一次您将能够在页面上看到该控件。

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

关于c# - 回发后不显示用户控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16606044/

相关文章:

用户控件中的 MVVM 文本框绑定(bind)到不同的类型

c# - .NET 线程如何等待不属于任何线程的 syncblk?

c# - Assembly.GetTypes - 如果 GetExportedTypes 可用,为什么要使用它?

c# - 什么是所有浏览器代理的东西?

c# - 工作环境的垃圾收集?

c# - 什么是 System.Web.Mvc ViewModels 的最佳实践

用于在 Windows 控制台中运行的游戏的 C++ 控件

javascript - 这些控件叫什么?

c# - 如何在 .Net Core 中使用自定义预处理器指令

C# Entity Framework 内存使用率高,内存泄漏?