Mogli
Mogli

Reputation: 2012

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?

Upvotes: 4

Views: 18248

Answers (4)

Vivek
Vivek

Reputation: 5165

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

Upvotes: 0

Yehuda Shapira
Yehuda Shapira

Reputation: 8630

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.

Upvotes: 4

rick schott
rick schott

Reputation: 21112

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.

Upvotes: 7

William
William

Reputation: 221

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

Upvotes: 0

Related Questions