How do you access Control.ViewState with a dynamically added Control subclass?
Question
We have created a control that needs to persist data via the ViewState property of the Control class. Our class subclasses control strictly to get access to the ViewState property (it's protected on the Page object). We are adding the control to Page.Controls in OnInit, and then attempt to set the ViewState property in OnPreLoad.
When we decode and examine the ViewState of the page, our values have not been written out, and are thus not available for later retrieval.
Does anyone know how we can get our control to participate in the ViewState process?
Solution
The issue is adding the control to the Page directly. Unfortunately this is too high up the controls hierarchy to participate in the Forms ViewState Handling. If you add the control onto the actual ASPNet Form's Controls collection somewhere then it will successfully participate in LoadViewStateRecursive and SaveViewStateRecursive.
OTHER TIPS
Try creating your control in OnInit, then add it to the Page.Controls during OnLoad.
ViewState isn't loaded until after OnInit, but before OnLoad.
Here's a rough outline of the Page Life-Cycle(GregMac) posted this in a response to an earlier question of mine.