自定义控件事件未触发 [英] Custom Control events not firing
问题描述
我有一个带有LinkButton的自定义控件.当我单击LinkButton时,其click事件不会触发.
I have a custom control with a LinkButton on it. When I click the LinkButton, its click event does not fire.
[ToolboxData("<{0}:View runat=server></{0}:View>")]
public class View : Control
{
private LinkButton lbNextPage;
protected override void CreateChildControls()
{
lbNextPage = new LinkButton() { ID = "lbNextPage", Text = "Next Page" };
lbNextPage.Click += delegate(object sender, EventArgs e)
{
Page.Response.Write("Event Fires!");
};
Controls.Add(lbNextPage);
}
}
我仅提取了负责呈现LinkButton及其事件的代码(上面包含了这些内容),以便删除所有其他因素.
I have extracted only the code responsible for the rendering of the LinkButton and its event (which is what is included above), so as to remove all other factors.
有人知道为什么不触发该事件吗?我想念什么吗?
Any idea why the event is not firing? Am I missing something?
推荐答案
主要是因为控件在页面生命周期中创建得太晚了.根据 MSDN生命周期文档,您需要创建任何动态控件在PreInit中,而不在CreateChildControls中.如果您要按原样开发自定义控件,则需要在Init覆盖中创建所有动态控件,并将事件挂接到那里.
It is essentially because the control is created too late in the page life cycle. As per the MSDN Lifecycle document, you need to create any dynamic controls in PreInit and not in CreateChildControls. If you're developing a custom control as you are, all your dynamic controls need to be created in an Init override and the events hooked up there.
希望这会有所帮助! :)
Hope this helps! :)
这篇关于自定义控件事件未触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!