C# UserControl 的事件处理程序没有触发
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/793621/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
UserControl's Event Handler not firing
提问by Mark Maslar
I dynamically load a UserControl into a View that's in a MultiView control. Although the UserControl adds an event handler, the event never fires.
我将 UserControl 动态加载到 MultiView 控件中的视图中。尽管 UserControl 添加了一个处理程序,但该永远不会触发。
What am I missing here? Thanks!
我在这里缺少什么?谢谢!
Containing ASPX page:
包含 ASPX 页面:
protected override void OnPreRender(EventArgs e)
{
if (MultiView1.ActiveViewIndex == 2) //If the tab is selected, load control
{
Control Presenter = LoadControl("Presenter.ascx");
(MultiView1.ActiveViewIndex.Views[2].Controls.Add(Presenter);
}
base.OnPreRender(e);
}
Presenter.ascx.cs
演示者.ascx.cs
override protected void OnInit(EventArgs e)
{
Retry.Click += this.Retry_Click; //This is a .Net 2.0 project
base.OnInit(e);
}
protected void Retry_Click(object sender, EventArgs e)
{
//This never fires
}
采纳答案by Dan Appleyard
I am thinking it is not firing because you are loading the control in your page's prerender event. Upon postback, the control is being lost because there is no view state for it. Therefore there is no control to fire its event. Try to load the control in the page's init event. Let us know what happens!
我认为它没有触发,因为您正在页面的预渲染中加载控件。回发时,控制正在丢失,因为它没有视图状态。因此,无控制触发其。尝试在页面的 init 中加载控件。让我们知道会发生什么!
回答by Jon
It sounds like the control is not being added after each post back, i would take out the if statement in the containing aspx page to see if that fixes the issue...im assuming Retry is a button?
听起来每次回发后都没有添加控件,我会取出包含 aspx 页面中的 if 语句,看看是否可以解决问题......我假设重试是一个按钮?
回答by mbillard
Postback event handling is done before rendering so the control is not present in the page in your case.
回发处理在呈现之前完成,因此在您的情况下,页面中不存在控件。
The life cycle events are fired in this order (skipped a few):
生命周期按以下顺序触发(略过一些):
- Init
- Load
- PreRender
- Unload
- 在里面
- 加载
- 预渲染
- 卸下
And event handling is done between Load and PreRender (in case some events change the way the page should be rendered, it makes sense).
处理在 Load 和 PreRender 之间完成(如果某些改变了页面的呈现方式,这是有道理的)。
So just move your code that loads the Retry control to Load or Init.
因此,只需将加载重试控件的代码移动到加载或初始化。
Reference: Asp.Net Page Life Cycle Overview
回答by amir ezati
The control must be visible initially to be able to enter in OnPreRender event. but maybe you want it to be unvisible. the be sure to have EnableViewState = false;
该控件最初必须是可见的,才能进入 OnPreRender 。但也许您希望它不可见。一定要有EnableViewState = false;