Maintain the state of dynamically added user control on postback?

I have a user control that contains only a text box and on another form I add this user control dynamically, a user can add the user control many times. I use a session variable to recreate the user control (maybe this approach doesn’t sound cool). After recreating the control the value of the textbox disappears, obviously. Is there any solution to maintain the state of the user control on postback?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

If you add dynamic controls back to the control during the correct Page Life Cycle event(PreInit) they will maintain their state through the IPostBackDataHandler interface.

PreInit – Create or re-create dynamic controls.

Method 2

I’ve had the same problem in the past.

What I did was give the dynamically-added control an ID, and made sure it retained that ID also on postback (in my case, I kept all the information in the session, and re-created the controls).

Once the postbacked control has the same ID as as before, Microsoft did magic and refilled the controls with the pre-postback values.

Method 3

Use the object cache. Add the usercontrol into the cache and retrieve it when you need it.

You can see a nice example of how this works at: ASP.net-Tutorials Cache and Object Cache.

I am also learning asp.net now and found that quite a nice explanation. I also used the Microsoft Library

Method 4

Every server control that inherits the IPostBackDataHandler interface has a LoadPostData method that processes the postback data. When control is implemented by a class (page, form, placeholders, controls etc), that class calls the LoadPostData method and passes the posted data and key to maintain control states.

All you need to do is to re-instantiate / reinitialize dynamic controls before or within page load event each and every time during postback and add this control to page / forms / placeholders. Then the posted data will automatically be assigned to the control by calling LoadPostData method by the parent control.

Check this article to learn how to write code for dynamic control –
How to maintain dynamic control events, data during postback in asp.net


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x