views:

37

answers:

1

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),its 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 didnt hit when i ran it.But the postback happens when i click the button.It comes to the PageLoad method.No idea why its not coming to my button click event.

Any ideas ? Thanks in advance.

+1  A: 

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.

lincolnk
then would the value remains there ? .Ex: for a textbox which i create dynamically and i want to read the value of it in a button click
Shyju
the value will remain the same, no worries :)
Genady Sergeev
However, I suggest that you move the control declaration to page_init
Genady Sergeev
Also, it is best to add the control(Button) during the page preinit so that the Viewstate is loaded to it. That may be a reason for your problem. Here is a link about the page life cycle: http://msdn.microsoft.com/en-us/library/ms178472.aspx
Robert