问题
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.
回答1:
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
}
回答2:
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);
回答3:
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.
来源:https://stackoverflow.com/questions/985556/add-asp-net-control-to-sharepoint-web-part