动态用户控件创建期间页面加载未命中(Web 表单)
我对以编程方式创建的用户控件有疑问。
根据我的测试,将用户控件添加到另一个控件的集合中会启动用户 控件的生命周期。具体来说,它调用控件的 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();
}
I have an issue with programatically created user controls.
From my tests, adding a user control to another control's collection kicks off the user
control's lifecycle. Specifically, it calls the controls Page_Load
method. Does anyone know if there is a way to kick off the
lifecycle of a user control BEFORE a call to the Controls.Add() method is
made?
Default.aspx code
<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 code
<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();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
请查看这篇文章:
http://msdn.microsoft。 com/en-us/library/ie/ms178472.aspx#catch_up_events_for_added_controls
对于动态加载的控件,它们的事件必须“赶上”。
但另一方面,为什么要关心 page_load 是在添加到页面的控件集合之前还是之后发生呢?由此产生的不良结果是什么?
Take a look at this article:
http://msdn.microsoft.com/en-us/library/ie/ms178472.aspx#catch_up_events_for_added_controls
For dynamically loaded controls, their events have to be "caught up".
But on the other hand, why would you care whether page_load occurs before or after it's added to the page's control collections? What is the unwanted result from this?
根据我的研究,无法使用 LoadControl() 方法触发控件的生命周期事件。解决方法是创建一个名为 Initialize() 的公共方法,如下所示:
在 Initialize() 方法中,可以执行将在 Page_Load 事件中完成的任何功能。
From my research, there is no way to trigger a control's life cycle events using the LoadControl() method. The workaround is to create a public method called Initialize() like so:
In the Initialize() method, any functionality that would be done in the Page_Load event can be executed.