加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-16 00:28:46 所属栏目:asp.Net 来源:网络整理
导读:我很难将具有自定义用户控件的页面直接修改到ASPX页面,现在需要在需要时将其动态加载。用户控件通过ASCX文件确实具有html和其他控件,并在代码隐藏中具有代码。 我已经阅读了多页,发现我无法直接实例化用户控件,但应该使用Page.LoadControl(…)。问题不是
我很难将具有自定义用户控件的页面直接修改到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;
            }

        }
    }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读