I’m attempting to add a group of controls to a page when a button is clicked. I need to add the same group of controls multiple times, possibly infinite times. Currently the add controls button click works, it’s when you click it the 2nd, 3rd, 4th…etc, time that it doesn’t work properly. It’s overriding and replacing the controls that are currently on the page, so only one group of controls is ever shown.
this is my code that creates and adds the controls, this happens in a click event
Label contactTypeLabel = new Label();
contactTypeLabel.Text = "Contact Type" + contactCount.ToString();
contactTypeLabel.ID = "contactLabel" + contactCount.ToString();
this.panelContacts.Controls.Add(contactTypeLabel);
DropDownList contactTypeDropDownList = new DropDownList();
//loading dropdown
this.panelContacts.Controls.Add(contactTypeDropDownList);
this.panelContacts.Controls.Add(new LiteralControl("<br />"));
this is the panel my controls are being added to..
<asp:UpdatePanel ID="UpdateContacts" runat="server">
<ContentTemplate>
<asp:Panel ID="panelContacts" runat="server">
</asp:Panel>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnAddContacts" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
What I ended up doing was using jQuery to create/remove the controls. Works much better and easier!
I believe a repeater would be your best bet.
http://xaeryan.blogspot.ca/2009/09/dynamically-adding-removing-textboxes.html
it allows your for dynamically adding new rows of whatever asp.net controls you need.
hope this helps,