简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM