在创建动态用户控件(Web窗体)期间未命中页面加载
本文关键字:加载 用户 动态 创建 控件 窗体 Web | 更新日期: 2023-09-27 18:22:08
我对用程序创建的用户控件有问题。
根据我的测试,将一个用户控件添加到另一个控件的集合中会启动用户控件的生命周期。具体来说,它调用控件Page_Load
方法。有人知道是否有办法启动在调用Controls.Add()方法之前,用户控件的生命周期为…制造的
Default.aspx代码
<asp:PlaceHolder1 ID="PlaceHolder1" runat="server" />
protected void Page_Init(object sender, EventArgs e)
{
var module = LoadControl("~/Module.ascx") as Module;
// If this line of code does not execute, the Page_Load method never executes in the user control.
//PlaceHolder1.Controls.Add(module);
}
Module.ascx代码
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<%# Container.DataItem %>
</ItemTemplate>
</asp:Repeater>
protected void Page_Load(object sender, EventArgs e)
{
Repeater1.DataSource = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
Repeater1.DataBind();
}
看看这篇文章:
http://msdn.microsoft.com/en-us/library/ie/ms178472.aspx#catch_up_events_for_added_controls
对于动态加载的控件,必须"赶上"它们的事件。
但另一方面,为什么要关心page_load是在添加到页面的控件集合之前还是之后发生?这会带来什么不想要的结果?
根据我的研究,没有办法使用LoadControl()方法触发控件的生命周期事件。解决方法是创建一个名为Initialize()的公共方法,如下所示:
var module = Page.LoadControl("~/Module.ascx") as Module;
module.Initialize();
在Initialize()方法中,可以执行在Page_Load事件中执行的任何功能。