I've new to .NET. I'm trying to add a button dynamically with an event. Initially, I have a button with a click event. The original button's click event response writes a test message and adds a button. The new button has a click event attached with a test message. Unfortunately, when I click the dynamically attached button, nothing happens. Could someone walk me throught this?

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:PlaceHolder ID="plh" runat="server">
            <asp:Button ID="btn_Click" Text="Click" runat="server" />
        </asp:PlaceHolder>
    </div>
    </form>
</body>
</html>

CODEFILE

public partial class dynamicEvent : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        btn_Click.Click +=new EventHandler(Clicked);
    }

    public void Clicked(object sender, EventArgs e)
    {
        Response.Write("Button One Clicked");
        Button btn = new Button();
        plh.Controls.Add(btn);
        btn.Text = "New Click";
        btn.Click += new EventHandler(btn_Click2);
    }

    void btn_Click2(object sender, EventArgs e)
    {
        Response.Write("Dynamic Button Clicked");
    }
}

Please read more about ViewState and Dynamic server controls.

protected void Page_Load(object sender, EventArgs e)
    {
        btn_Click.Click += new EventHandler(Clicked);
    
        if (Request["btn_Click"]!=null)
        {
            ViewState["btnClicked"] = true;
            
        }
        if (ViewState["btnClicked"] != null)
        {
            AddMyButton();
        }
    }
    void AddMyButton()
    {
        Button btn = new Button();
        
        btn.ID = "NewB";
        btn.Text = "New Click";
        btn.Click += new EventHandler(btn_Click2);
        plh.Controls.Add(btn);
    }
    public void Clicked(object sender, EventArgs e)
    {
        Response.Write("Button One Clicked");
        
    }

    void btn_Click2(object sender, EventArgs e)
    {
        Response.Write("Dynamic Button Clicked");
    }

I'll check out your recommended link. I appreciate the advice. Thanks for your help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.