Dynamically adding buttons and there events
-
Hi I hope some one can help me with this because it is driving me mad. I am using c# asp.net 2 and I am trying to add a button dynamically to the web page on a post back from when a user clicks an asp.net button. I am able to add the buttons dynamically, however I am unable to use any events that go with them. I have been reading a lot of articles and they say if you want to add a button dynamically you have to add it in the page load event. I have tried this and yet still the events for the buttons do not work. I am guessing that all the articles I have read are for asp.net 1.1 Does any one know how to add buttons dynamically and use there events under .net 2 for asp.net with c#. Thx for any help Scott.
-
Hi I hope some one can help me with this because it is driving me mad. I am using c# asp.net 2 and I am trying to add a button dynamically to the web page on a post back from when a user clicks an asp.net button. I am able to add the buttons dynamically, however I am unable to use any events that go with them. I have been reading a lot of articles and they say if you want to add a button dynamically you have to add it in the page load event. I have tried this and yet still the events for the buttons do not work. I am guessing that all the articles I have read are for asp.net 1.1 Does any one know how to add buttons dynamically and use there events under .net 2 for asp.net with c#. Thx for any help Scott.
Below is a quick example for what you might want to do:
<%@ Page Language="C#" %>
<script runat="server">protected void Page\_Load(object sender, EventArgs e) { if (ViewState\["DynamicButtonAdded"\]!=null) { Button dynamicButton = new Button(); dynamicButton.Text = "Dynamic Button"; PlaceHolder1.Controls.Add(dynamicButton); dynamicButton.Click += delegate { Response.Write("Dynamic Button Clicked"); }; } } protected void Button1\_Click(object sender, EventArgs e) { if (ViewState\["DynamicButtonAdded"\] == null) { Button dynamicButton = new Button(); dynamicButton.Text = "Dynamic Button"; PlaceHolder1.Controls.Add(dynamicButton); ViewState\["DynamicButtonAdded"\] = true; } }
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Add Dynamic Button" On_Click="Button1_Click" />
<br />
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</div>
</form>
</body>
</html>