Can you please tell me what's wrong with the following code?
Panel div = new Panel();
Button btn1 = new Button { Text = "Delete", CommandArgument = "argument", ID = "remove" };
Button btn2 = new Button { Text = "Insert", CommandArgument = "argument2", ID = "insert" };
btn1.Click += new EventHandler(btn_click);
btn2.Click += new EventHandler(btn_click);
div.Controls.Add(btn1);
div.Controls.Add(btn2);
ph_plan.Controls.Add(div); // where ph_plan is a placeholder in the user control
protected void btn_click(object sender, EventArgs e)
{
Button btn = (Button)sender;
if(btn.ID == "remove")
// do this
else
// do that
}
The code above occurs right after a click on a button in the user form. It is supposed to create 2 new buttons with events assigned. Indeed, it creates the buttons but when I click them nothing happens. I guess the events cannot be registered. What am I doing wrong here?
The reason this is happening is because
Page
is a stateless class and once it renders everything, it is destroyed. Therefore, once you have a postback, this information is lost and yourPage
class has no knowledge of the button's events since the dynamic buttons were not part of theaspx
file.You need to maintain a collection of the dynamic controls that you've created, possibly in a session, so that they can be recreated after a postback. There's an example of it here.
How to create multiple control in asp.net with event:
This code will print every button id that have been created at runtime in page load event.