views:

2155

answers:

1

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!

+3  A: 

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.

Welbog
Interesting, I did almost exactly that just in the Page_Init event. I wasn't aware you could even create controls in the Page_Load event... thanks!
John Rasch