Our 100th Tip of the Day! Control State

Posted Tuesday, May 10, 2005 8:27 AM by C-Dog's .NET Tip of the Day
I can't believe we have 100 tips out there now.  Hopefully someone is reading this and finding it some what useful.  I am hoping these tips will be a useful reference when we start using 2.0 more and more. 
A new way of maintaining state is available through something called Control State.  Although Control State is not nearly as convenient to use (i.e.: ViewState[IsMarcusLame] = true).  It still can be very useful for controls.  Technically, control state is still stored in the same View Sstate string, but the difference is control state can not be disabled (even when viewstate is disabled by the page or application).   
I said it is less convenient and here is why.  For a control to use Control State, it must make a call to the RegisterRequiredControlState method of the Page object in the OnInit override.   Secondly you must override the LoadControlState and SaveControlState events to manually get your objects out of the control state.  That is truly the part that sucks.
Here is a simple example, of the amount of code that is required just to store one field.
public class SampleControl : Control
  string color = "black";
  protected override void OnInit(EventArgs e)
  protected override void LoadControlState(
                          object savedState)
    object[] state = (object[])savedState;
    color = (string)state[1];
  protected override object SaveControlState()
    object[] state = new object[2];
    state[0] = base.SaveControlState();
    state[1] = color;
    return state;
As you can see, it requires quite a bit of code to make it happen.  So this might not be ideal, but it is at least a good idea for you to know its out there.

Read the complete post at http://www.dotnettipoftheday.com/blog.aspx?id=126