我很难将具有自定义用户控件的页面直接修改为 ASPX 页面,现在需要仅在需要时动态加载它。用户控件确实通过 ASCX 文件具有 html 和其他控件,并且在代码隐藏中具有代码。
我已阅读多页,发现我无法直接实例化用户控件,但应该使用Page.LoadControl(...)
。问题不在于编译,而是当页面加载控件时,ASCX 内的所有控件都为空,然后崩溃。
如何动态使用在 ASCX 和代码隐藏中具有代码的用户控件?
Edit:
我正在做的示例(页面加载或 Page_PreRender 或 Page_PreInit)
Control c = LoadControl(typeof(MyControl), null);
myControl= (MyControl)c;
myControl.ID = "123";
myControl.Visible = false;
Controls.Add(myControl);
MyControl 确实有例如<div id="whatever" runat="server">
...并且在 MyControl 内部它将可见性设置为 True 或 False...但是当它这样做时,现在它崩溃了,因为“无论”div 是 NULL。
我所做的是使用Page.LoadControl
方法中的Page_Init
将自定义用户控件添加到页面上的占位符。
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;
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)