Preserving the state in dynamic asp.net usercontrols

Phew 2007… my new years resolution includes writing more posts, but you know how these things go ;-)

I recently struggled with the ascx user controls in asp .net v1.1. My problem was that when creating user controls dynamically, the state was not preserved between postbacks and at first I couldn’t figure out why. Once I understood the process of the asp .net page request completely by reading through this informative article Understanding ASP.NET View State I finally figured out the two essential things you have to do:

  • Specify IDs for the dynamic controls. If you just use Page.loadControl() and add the control to the page without defining it’s id, .net will not be able to save and restore it’s viewstate – so the ID is essential.
  • Recreate the user control on every page load (post back). Even though .net stores the viewstate information when you provided the ID, the user controls will not survive a post back – this is by design. So it’s your responsibility to recreate your user controls on page load which means you have to know the control (path to ascx-file) with it’s corresponding ID and restore those.
  • An example can be found in the aspnet4you article Dynamic Loading of User Control with ViewState Preserved.

When I finally got that, I developed a modified PlaceHolder-Control, which encapsulates the dynamic loading and reloading of viewstate enabled user controls. I currently don’t have a decent version to post here, though.

Btw, I just updated the SQL Script Creator project page with a slightly changed version 1.0.1 and also uploaded the source code. The program is now officially open sourced under the GPL.