Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net dynamically added user control saving values after postback

Here's my issue. I have a usercontrol that I want to allow users to add as many instances of as necessary using a button click (each time a button is clicked, I want to add another instance of my user control to a Panel). It works fine the first time, but each additional post back removes all of the added controls. I have no problem keeping track of the number of user controls a user has added but how do I ensure they stay in the same state they were before the postback? I've read some posts about people using SaveViewState and LoadViewState but I haven't been able to find any examples.

My biggest issue is ensuring that all of the text boxes and dropdownlists from each user control stays populated with the same text/selected value/data after each post back

Thanks in advance, Ben

like image 929
Ben Avatar asked Oct 15 '10 19:10

Ben


1 Answers

Since you're programmatically adding controls to your page, you'll need to recreate them on EACH postback.

Also, it's necessary that you recreate programmatically added controls on PreInit or Init event of the page. This is for proper viewstate restoring event management.

If you don't do this, control will be gone on postback and they won't handle any event.

EDIT

Although is recommended to add dynamically controls on PreInit or Init it's true (as Dustin Hodges says) that it may work if you add them on page_load. I'd say you should avoid it unless you have no other option.

You may be able to get away with loading your controls in the Page_Load event handler and maintaining the view state properly.
It all depends on whether or not you are setting any properties of the dynamically loaded controls programmatically and, if so, when you're doing it relative to the Controls.Add(dynamicControl) line.
A thorough discussion of this is a bit beyond the scope of this article, but the reason it may work is because the Controls property's Add() method recursively loads the parent's view state into its children, even though the load view state stage has passed.

Source MSDN

like image 183
Claudio Redi Avatar answered Sep 19 '22 03:09

Claudio Redi