ASP.NET ViewState Tips and Tricks #1
        Posted  
        
            by João Angelo
        on Exceptional Code
        
        See other posts from Exceptional Code
        
            or by João Angelo
        
        
        
        Published on Mon, 05 Mar 2012 12:41:15 +0000
        Indexed on 
            2012/03/19
            2:14 UTC
        
        
        Read the original article
        Hit count: 459
        
In User Controls or Custom Controls DO NOT use ViewState to store non public properties.
Persisting non public properties in ViewState results in loss of functionality if the Page hosting the controls has ViewState disabled since it can no longer reset values of non public properties on page load.
Example:
public class ExampleControl : WebControl
{
    private const string PublicViewStateKey = "Example_Public";
    private const string NonPublicViewStateKey = "Example_NonPublic";
    // DO
    public int Public
    {
        get
        {
            object o = this.ViewState[PublicViewStateKey];
            if (o == null)
                return default(int);
            return (int)o;
        }
        set { this.ViewState[PublicViewStateKey] = value; }
    }
    // DO NOT
    private int NonPublic
    {
        get
        {
            object o = this.ViewState[NonPublicViewStateKey];
            if (o == null)
                return default(int);
            return (int)o;
        }
        set { this.ViewState[NonPublicViewStateKey] = value; }
    }
}
// Page with ViewState disabled
public partial class ExamplePage : Page
{
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        this.Example.Public = 10; // Restore Public value
        this.Example.NonPublic = 20; // Compile Error!
    }
}
© Exceptional Code or respective owner