I have a visual web-part for sharepoint with code below, but code of click-handler is never firing. What’s wrong with my code?:
protected Button btApply;
protected void Page_Load(object sender, EventArgs e)
{
... some code ...
btApply = new Button();
btApply.Text = "Apply";
btApply.CssClass += "InputControl";
btApply.Click += new EventHandler(btApplyClick);
this.Controls.Add(btApply);
... some code ...
}
protected void btApplyClick(object sender, EventArgs e)
{
... some code ...
}
If you are to create controls dynamically, you have to to it in
Page_PreInit. A quote fromMCTS Self-Paced Training Kit (Exam 70-515): Web Applications Development with Microsoft .NET Framework 4, page 106:The page (as well as web-part, user control, etc.) lifecycle is explained in MSDN “ASP.NET Page Life Cycle Overview” article.
Also, see the quite similar question Event for Dynamically created Controls in ASP.Net
So, just move your control creation and event wiring-up into
Page_PreInitand you should be fine.