Logo Home   Documents and Lists   Create   Site Settings   Help   
Icon
Dan Kohls' Weblog
Blog: Easy Control State for ASP.NET 1.0 & 1.1
   
New New Item
|
Edit Edit Item
|
Delete Delete Item
|
Alert Me
|
Go Back to List
Title:
Easy Control State for ASP.NET 1.0 & 1.1
Body:
When building your own control ASP.NET, it is often useful to store some of the control's properties in ViewState.  However, ViewState is not guantanteed to always be available; it can be turned off at the Page or Application level, thereby crippling your control.  Microsoft recognized this with version 2.0 or ASP.NET and introduced the concept of ControlState.
 
For those of us not fortunate enough to be able to use ASP.NET 2.0 all the time, I came of with the following solution:
 
Build your code behind properties using the following example:
 
 public class WeekNavigator : System.Web.UI.UserControl
 {
  protected System.Web.UI.HtmlControls.HtmlInputHidden ControlState;
...
  public DateTime SelectedWeek
  {
   get
   {
    if( ControlState.Value.Length==0 )
     return DateRangeStart( DateTime.Now );
    else
    {
     byte[] utfBytes = Convert.FromBase64String(ControlState.Value);
     string uncodedState = System.Text.Encoding.UTF8.GetString(utfBytes);
     return DateRangeStart( DateTime.Parse(uncodedState) );
    }
   }
   set
   {
    byte[] utfBytes = System.Text.Encoding.UTF8.GetBytes(value.ToString());
    string base64 = Convert.ToBase64String(utfBytes);
    ControlState.Value = base64;
   }
  }
...
}
 
In the .ASCX file, add the following control:
<input type="hidden" id="ControlState" runat="server">
 
Draft:
No
Attachments:
 
 
Created at 4/14/2006 11:40 AM by Dan Kohls
Last modified at 4/24/2006 9:05 AM by Dan Kohls