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; } } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- 限制面向公众的asp.net应用程序演示站点?
- asp.net – PHP的require_once()是否有ASP MVC等效?
- asp.net-core – ASPX.NET核心 – IIS服务器上的随机502错误
- asp.net-mvc – 从.Net MVC View获取HTML而不实际在浏览器中
- asp.net – 只能将一个ScriptManager实例添加到页面中
- ASP.Net中父/子UI设计的最佳实践?
- asp.net-mvc – 防止JsonResult自动格式化日期
- asp.net – 在DataTable.Select中使用BETWEEN
- asp.net – 为什么设置为SqlServer时会话超时不起作用?
- asp.net-mvc – 如何使用ASP.NET MVC实现自定义缓存提供程序
推荐文章
站长推荐
- asp.net – 你能使用基于属性的WebApi 2与WebFor
- asp.net – 由TaskScheduler和SynchronizationCo
- ASP.NET会员密码重置
- 最好的ASP.net WYSIWYG
- asp.net-mvc – 如何将Azure AD身份验证用于单独
- asp.net-core – app.UseErrorHandler()可以访问
- asp.net-mvc-3 – ASP.NET Web API问题 – 授权/
- asp.net – 使用IIS(localhost)测试时重新学习的
- asp.net级联下拉与差异
- asp.net-mvc – jQuery脚本包含在mvc 4模板的页面
热点阅读