ASP.NET自定义用户控件动态地添加 [英] ASP.NET Custom user control to add dynamically

查看:160
本文介绍了ASP.NET自定义用户控件动态地添加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我也很难有时间去修改一个页面,直接有一个自定义用户控件的ASPX页面,现在需要对只有需要的时候动态加载。用户控件确实有通过ASCX文件,HTML和其他控件,并已在code-背后code。

I have hard time to modify a page that had a Custom User Control directly to the ASPX page and now require to have it dynamically loaded when needed only. The User Control does have html and other controls via the ASCX file and has code in the code-behind.

我已阅读多页,并发现我不能直接实例用户控制,而应使用 Page.LoadControl(...)。问题不在于编译,但是当页面加载控件它发生了内ASCX所有控件都为空,然后崩溃。

I have read multiple page and have found that I cannot instantiate directly the User Control but should use the Page.LoadControl(...). The problem is not the compiling but when the page load the control it happen that all controls inside the ASCX are null and then crash.

我如何使用具有code在ASCX和$ C $用户控件C-背后动态?

How can I use a User Control that has code in the ASCX and in the code-behind dynamically?

什么我正在做的例子(pageLoad的或页面preRender或页面preINIT)

Example of what I am doing in (PageLoad or PagePreRender or PagePreInit)

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

MyControl确实有例如< D​​IV ID =无所谓=服务器> ...和MyControl里面的可见性设置为True或假的... ...但是当它这样做,现在它崩溃,因为任何分区是NULL。

MyControl does have for example <div id="whatever" runat="server">... and inside the MyControl it set the visibility to True or False... but when it does that, now it crash because the "whatever" div is NULL.

推荐答案

我所做的就是使用Page.LoadControl方法在Page_Init的自定义用户控件添加到一个占位符在页面上。

What I have done is use the Page.LoadControl method in the Page_Init to add the custom user control to a place holder on the page.

 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);

}

这对我来说工作得很好。

This works fine for me.

下面是code的动态加载的用户控件:

Here is the code for the dynamically loaded user control:

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;
            }

        }
    }

这篇关于ASP.NET自定义用户控件动态地添加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆