John Rasch John Rasch -3 years ago 44
ASP.NET (C#) Question

Dynamically add multiple instances of the same user control type when button is clicked

Is it possible to add instances of the same user control when an "add" button is clicked and maintain ViewState?

The user interface here is similar to the Gmail file-attachment process, where the user can click "attach another file" and another file upload box appears.

My page is surrounded by an UpdatePanel. I am able to get 1 control to load, but the button's click event fires after the Placeholder_Init method. I tried storing an integer in the ViewState that kept track of the number of user controls that should be rendered, but the Init method is also fired before the ViewState is restored.

Thanks!

Answer Source

Adding multiple controls dynamically is easy in ASP.NET. Let's say you have a panel named Panel declared in your ASPX file and you have a custom control called MyControl.

In your Page_Load function (or indeed pretty much anywhere), add something like the following:

for (int i = 0; i < NumberOfAttachments; i++) {
    Panel.Controls.Add(new MyControl());
}

This works for UpdatePanels, too, but you'll need to call the .Update() function to get it to update on the client side if you don't have it to update on child postback.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download