Friday, January 09, 2009

Creating Dynamic User Controls with ViewState _from_ ViewState

I will write a really short post here, maybe I'll complete it later. I had to create some controls dynamically on a page. I used a ViewState saved property to determine the type of the control I would load (in Page_Load). It all worked fine until I've decided to add some ViewState saved properties in the dynamic controls. Surprise! The dynamically created controls did not persist their ViewState and my settings got lost on postback.

It's a simple google search away: dynamically controls created in Page_Load have empty ViewState bags. You should create them in Page_Init. But then again, in Page_Init the page doesn't have any ViewState, so you don't know what control type to load. It seemed like a chicken and egg thing until I tried the obvious, since the ViewState is loaded in the LoadViewState method, which is thankfully protected virtual, why not create my control there, after the page loads its view state? And it worked.

Bottom line:
protected override void LoadViewState(object savedState)