ASP.NET自定义用户控件动态添加
发布时间:2020-05-23 18:06:23 所属栏目: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;
}
}
} (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- ASP.NET Web API控制器专用串行器
- asp.net-mvc – 设置Kendo UI Grid Popup(MVC)的宽度
- asp.net – 如何从复选框列表中获取最新的选定值?
- asp.net-mvc-3 – ASP.NET MVC DropDownListFor从模型中选择
- ASP.NET MVC授权:角色的权限
- asp.net – 使PDF显示内联而不是单独的Acrobat Reader窗口
- asp.net – 如何配置IIS以接受POST请求?
- asp.net-mvc – System.Web.Mvc.ActionFilterAttribute vs
- asp.net-mvc – 为什么要使用视图模型?
- asp.net – 禁止从网页复制数据
推荐文章
站长推荐
- 当ASP.NET验证失败时,更改文本框的css类
- ASP.NET页面方法vs Web服务
- asp.net c#membership:如何做一个GetUsersInRol
- asp.net – 为什么我不能使用NuGet删除包?
- 使用StateServer的ASP.NET会话混合(SCARY!)
- asp.net – 访问视图Mvc.net中的路由值
- asp.net-mvc – ASP.NET MVC领域:它们对大型应用
- asp.net-mvc – 使用Visual Studio 2013 Preview
- asp.net – Live Sitecore网站的Git Source Cont
- asp.net-web-api – ember-data:根据需要加载ha
热点阅读
