Create onClick event for dynamically created button asp.net

This is my .aspx page

<asp:Panel ID="Panel1" runat="server">
    <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
    <asp:Label ID="Label1" runat="server"></asp:Label>
</asp:Panel>    

This is my aspx.cs page

public partial class Test : System.Web.UI.Page
{
    protected void Button1_Click(object sender, EventArgs e)
    {
        Button button2 = new Button();
        button2.Text = "Dynamic Button";
        button2.Click += new EventHandler(button2_Click);
        Panel1.Controls.Add(button2);
    }

    void button2_Click(object sender, EventArgs e)
    {
        Label1.Text = "working";
    }

    protected void Page_Load(object sender, EventArgs e)
    {

    }
}

"button2"'s click even does not work. I also tried:

button2.Click += button2_Click;

But that does not seem to work either. If I place the code in the "Page_Load" function, it works. But I want the dynamic button to be added to the page on clicking the first button (i.e. Button1).

How do I make this work??


ANSWERS:


Probably you can have both the buttons in your aspx page with onclick property event defined for each of the buttons. Just keep the button2 visibility as false initially and onclick of button1 you can make the visibility of button2 as true. It's not a generic answer. It is a quick turnaround to your question specifically


You can add a PlaceHolder to your Panel:

<asp:Panel ID="Panel1" runat="server">
    <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
    <asp:Label ID="Label1" runat="server"></asp:Label>
    <asp:PlaceHolder ID="ph" runat="server" />
</asp:Panel>

and insert the button in it, making sure that it is recreated on each postback:

protected void Button1_Click(object sender, EventArgs e)
{
    CreateDynamicButton();
    ViewState.Add("Button2", "Yes");
}

protected void CreateDynamicButton()
{
    Button button2 = new Button();
    button2.ID = "button2";
    button2.Text = "Dynamic Button";
    button2.Click += new EventHandler(button2_Click);
    ph.Controls.Clear();
    ph.Controls.Add(button2);
}

protected override void CreateChildControls()
{
    base.CreateChildControls();
    if (ViewState("Button2") == "Yes")
    {
        CreateDynamicButton();
    }
}

void button2_Click(object sender, EventArgs e)
{
    Label1.Text = "working";
}


 MORE:


 ? Dynamically Add Click event to asp button
 ? Dynamically Add Click event to asp button
 ? Dynamically Add Click event to asp button
 ? Button Click Event Getting Lost
 ? Dynamically assign button events in c# asp.net
 ? 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