0

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;
    }
}
3
  • what exactly is list ? list.Controls.add ? you need to add the button to your Form. <form id="form1" runat="server">, try Form1.Controls.add(button) Commented Dec 31, 2012 at 14:00
  • I used as list: <ul id="list" runat="server"></ul> Commented Dec 31, 2012 at 14:03
  • What does your page_load code look like? Commented Dec 31, 2012 at 14:20

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I think at least for the first time when I click, the first firing should be, isn't it? because I create it?
The first add can be in your page_load. AFter that they need to be done in the pre_init event.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.