Custom Control events not firing

半城伤御伤魂 提交于 2019-12-08 08:17:49

问题


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);
    }
}

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?


回答1:


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! :)



来源:https://stackoverflow.com/questions/471260/custom-control-events-not-firing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!