ASP.NET自定义用户控件动态添加

我很难将具有自定义用户控件的页面直接修改到ASPX页面,现在需要在需要时将其动态加载。用户控件通过ASCX文件确实具有html和其他控件,并在代码隐藏中具有代码。

我已经阅读了多页,发现我无法直接实例化用户控件,但应该使用Page.LoadControl(…)。问题不是编译,而是当页面加载控件时,ASCX中的所有控件都为空,然后崩溃。

如何动态地使用在ASCX和代码隐藏中的代码的用户控件?

编辑:

我在做什么的例子(PageLoad或PagePreRender或PagePreInit)

Control c = LoadControl(typeof(MyControl),null);
      myControl= (MyControl)c;
      myControl.ID = "123";
      myControl.Visible = false;
      Controls.Add(myControl);

MyControl确实有例如< div id =“any”runat =“server”> …并且在MyControl内部将可见性设置为True或False …但是当它这样做时,现在它崩溃了,因为“任何“div”为空。

解决方法

我所做的是使用Page_Init中的Page.LoadControl方法将自定义用户控件添加到页面上的占位符。
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);

}

这对我来说很好。

以下是动态加载的用户控件的代码:

MyControl.ascx.cs

public partial class MyControl : System.Web.UI.UserControl
    {
        protected void Page_Init(object sender,EventArgs e)
        {
            LiteralControl lit = new LiteralControl("Test Literal Control");
            Page.Controls.Add(lit);
        }
        protected void Page_Load(object sender,EventArgs e)
        {
            whatever.Visible = true;

            if (IsPostBack)
            {
                whatever.Visible = false;
            }

        }
    }

相关文章

引言 本文从Linux小白的视角, 在CentOS 7.x服务器上搭建一个...
引言: 多线程编程/异步编程非常复杂,有很多概念和工具需要...
一. 宏观概念 ASP.NET Core Middleware是在应用程序处理管道...
背景 在.Net和C#中运行异步代码相当简单,因为我们有时候需要...
HTTP基本认证 在HTTP中,HTTP基本认证(Basic Authenticatio...
1.Linq 执行多列排序 OrderBy的意义是按照指定顺序排序,连续...