Preserving the state in dynamic 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.

SQL Script Creator released

New Version of SQL Script Creator Logo
I continued the development of my SQL Script Creator and have just put up a setup package on it’s project page. It is a handy tool to create a sql script from query meta data based on several templates and can save you quite some time when working with temporary tables or cursors in SQL Server.

Meanwhile I found a similar opensource program which is called iCodeGenerator which uses user editable templates to create custom scripts and code but it bases it’s generation on a table rather than a more customizable select query.

In case you are wondering: The splashscreen design is drawn by hand with a graphic tablet – it gave me the chance to try some brush effects. It is no coincidence that the content resembles the SQL Server 2005 splash screen in a more “handmade” style ;-)