Nana
Nana

Reputation: 31

Click event doesn't fire

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 ...
}

Upvotes: 0

Views: 1007

Answers (1)

J0HN
J0HN

Reputation: 26951

If you are to create controls dynamically, you have to to it in Page_PreInit. A quote from MCTS Self-Paced Training Kit (Exam 70-515): Web Applications Development with Microsoft .NET Framework 4, page 106:

You can add controls to a form at run time by handling the Page.PreInit event (if you are not using master pages) or the Page.Init event (if you are using master pages and you are adding the control to a content page)

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_PreInit and you should be fine.

Upvotes: 1

Related Questions