views:

534

answers:

3

Hi.

I'd like to dynamically add an ASP.NET LinkButton to my SharePoint web part. I'm hooking the LinkButton up with an event-handler, but when I execute the code it seems the event is never fired.

Where in the life-cycle (which event) should I add such a control and how?

Thanks.

+3  A: 

Add it in the CreateChildControls() event in the webpart, like:

protected override void CreateChildControls()
{      
    LinkButton linkbutton = new LinkButton();
    linkbutton.Click += ClickButton;
    this.Controls.Add(linkbutton);

}

protected void ClickButton(object sender, EventArgs e)
{
    // handle event
}
Johan Leino
+2  A: 

If you need to have the control fire a server event you need to register the control in the Page_Init or Page_Load life cycle for the event to fire. If you add the control in the PreRender phase then it is to late. Or override the CreateChildControls() method and add the control in that method.

You should not need to do anything special to add the control, just:

    var linkButton = new LinkButton();
    // register event
    Controls.Add(linkButton);
    

Torkel
A: 

I've had the same issue. By adding the LinkButton in CreateChildControls and explicitly setting the ID and then decorating my WebPart with the INamingContainer interface fixed my problem.

Colin