0

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");
    }
}

Edited by __avd: Add [code] tags. Encase your code in: [code] and [/code] tags.

2
Contributors
2
Replies
3
Views
8 Years
Discussion Span
Last Post by djscratch
0

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");
    }
0

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

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.