简体   繁体   中英

Why my dynamically added event handler method is not firing in asp.net page?

In my asp.net page codebehind, I am creating a button dynamically and adding a event handler to it. But when i set a breakpoint on the button click event (which I added in codebehind), it's not hitting. Any idea why?

My code is here

ASP.NET PAGE

<form runat="Server" id="frm1">
   <div id="divPaymentOptions" runat="Server"> </div>
</form>  

CODEBEHIND (C#)

 protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
          LoadControl();
        }
    }
 private void LoadControl()
 {
     Button objTempBtn = new Button();
     objTempBtn.ID = "myDynamicBtn";
     objTempBtn.Text = "Clich me";
     objTempBtn.Click+=new EventHandler(objTempBtn_Click);
     this.divPaymentOptions.Controls.Add(objTempBtn);
 }

 private void objTempBtn_Click(object sender, EventArgs e)
 {
    string strMsg="want to do something here";
 }

I put a breakpoint on divPaymentOptions. But that didn't hit when I ran it. But the postback happens when I click the button. It comes to the PageLoad method. No idea why it's not coming to my button click event.

Any ideas?

the button doesn't exist during the postback. if you dynamically add a control to the page, you have to do it every time. take out the check for !IsPostBack and it should work.

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