Pat*_*ins 21 asp.net user-controls webforms dynamic
我很难将具有自定义用户控件的页面直接修改为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);
Run Code Online (Sandbox Code Playgroud)
MyControl确实有例如<div id="whatever" runat="server">......并且在MyControl中它将可见性设置为True或False ...但是当它这样做时,现在它崩溃了,因为"whatever"div是NULL.
ora*_*dov 42
我所做的是使用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);
}
Run Code Online (Sandbox Code Playgroud)
这对我来说很好.
以下是动态加载的用户控件的代码:
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
43488 次 |
| 最近记录: |