Web 表单 UserControls - LoadControl 在预初始化或 page_load 中?
在 MSDN 页面生命周期参考中,它指出预初始化用于“创建或重新创建动态控件”。
然而,MSDN 上的其他地方,有一个示例暗示动态用户控件应该是在Page_Load中加载的,
这是矛盾吗?或者 pre-init 仅用于标准 aspx 控件?
我错过了什么:)
编辑: 然而,无论哪种方法都有效,一种方法可能比另一种方法有一些好处。
(WebUserControl1 是一个具有简单标签属性 SomeProperty 的 UserControl)
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
WebUserControl1 wc1 = LoadControl(@"~\WebUserControl1.ascx") as WebUserControl1;
wc1.SomeProperty = "Hello World";
Controls.Add(wc1);
}
protected void Page_Load(object sender, EventArgs e)
{
WebUserControl1 wc1 = LoadControl(@"~\WebUserControl1.ascx") as WebUserControl1;
wc1.SomeProperty = "Hello World";
Controls.Add(wc1);
}
In the MSDN page lifecycle reference it states that the pre-init is used to "Create or re-create dynamic controls."
However, elsewhere on MSDN, an example implies that a dynamic user control should be loaded in Page_Load
Is this a contradiction? Or is pre-init used only for standard aspx controls?
What have I missed :)
Edit:
Either way works, however, there is presumably some benefit of one approach over the other.
(WebUserControl1 is a UserControl with a simple label property, SomeProperty)
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
WebUserControl1 wc1 = LoadControl(@"~\WebUserControl1.ascx") as WebUserControl1;
wc1.SomeProperty = "Hello World";
Controls.Add(wc1);
}
protected void Page_Load(object sender, EventArgs e)
{
WebUserControl1 wc1 = LoadControl(@"~\WebUserControl1.ascx") as WebUserControl1;
wc1.SomeProperty = "Hello World";
Controls.Add(wc1);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
答案是这取决于您的自定义控件。如果您的用户控件不需要在 page_load 之前发生任何事情,那么您可以继续在页面加载期间添加您的控件,如果您的用户控件中有在较早时间执行的代码,那么您应该在正如 MSDN 文章所建议的,早期阶段。
The answer is it depends on your custom control. If your user control doesn't need anything to happen before page_load, then you can go ahead and add your control during page load, if you have code in your user control that executes at an earlier time, then you should add your control at an earlier stage as the MSDN article suggests.
你到底想做什么?您是否试图将信息传递给用户控件?如果是这样,您可以在 page_load 事件中从父页面将信息传递给用户控件。
What exactly are you trying to do? Are you trying to pass information to the user control? If so you can pass the information to the user control in the page_load event from the parent page.