views:

1162

answers:

1

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  A: 

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

Ray Booysen