Stack User
Stack User

Reputation: 1398

Dynamical Asp.net Button not fired

In my program I used a dynamically button with below code:

Button button = new Button();  
button.ID = counter.ToString();
button.Text = "ok";
button.Click += new EventHandler(this.ButtonClick);

list.Controls.Add(button);

And I have added click event's code like below:

private void ButtonClick(object sender, EventArgs e)
{
    //..
}

There are several solutions:

C# Button Not Firing?

Dynamically created button not firing Click event

I have read and apply them but I cannot solve the problem.

My dynamic button operation is placed in Page_Load. (I tried it in Page_Init and it wasn't fired again.)

In order to debug I use break point. I put it to the Page_Load, for the first time the page works and the program stops at the break point, and then I continue.. After I click the dynamic button, the code wasnot fired...

My Page_Load like below:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
         //..
         case "button":

         Button button = new Button();  
         button.ID = counter.ToString();
         button.Text = "ok";
         button.Click += new EventHandler(this.ButtonClick);


         list.Controls.Add(button);
         break;
    }
}

Upvotes: 0

Views: 238

Answers (2)

Rahul Murari
Rahul Murari

Reputation: 449

To create dynamic button control in web form, please give offset value to button where you want.

Upvotes: 0

Chad Ruppert
Chad Ruppert

Reputation: 3680

When you dynamically create controls in webforms, you need to recreate them dynamically AGAIN every postback.

Make sure you learn the lifecycle for webforms pages, and reregister the controls BEFORE the event fires, during the pre-init phase.

Upvotes: 2

Related Questions