Dynamically assign button events in c# asp.net

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?


ANSWERS:


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 your Page class has no knowledge of the button's events since the dynamic buttons were not part of the aspx 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:

string[] arg = new string[10];

protected void Page_Load(object sender, EventArgs e)
{

    for (int i = 0; i < 10; i++)
    {
        LinkButton bb = new LinkButton();
        arg[i]= bb.ID = "bb" + i.ToString();
        bb.Text = "like"+"<br/>";
        Panel1.Controls.Add(bb);
        bb.Click += new EventHandler(bb_Click);
    }
}

void bb_Click(object sender, EventArgs e)
{
    LinkButton btn = (LinkButton)sender;
    for (int j = 0; j < 10; j++)
    {
        if (btn.ID == arg[j])
        {
            btn.Text = "";
            btn.Text = "unlike";
            Response.Write(arg[j]);
        }
    }
}

This code will print every button id that have been created at runtime in page load event.



 MORE:


 ? how to create an asp button dynamically and add event to it
 ? C# how to handle multiple button click events?
 ? C# Add Controls To Panel In a Loop
 ? C# Add Controls To Panel In a Loop
 ? C# Add Controls To Panel In a Loop
 ? dynamically adding buttons and button objects in panel
 ? Populate Buttons With Database Values c#
 ? Adding GUI controls dynamically
 ? trying to add/remove controls to a form
 ? removing dynamically created controls C#