title: ViewState Variable Reset After Postback
body: <p>I've seen this problem a lot, and it's usually because the <code>ViewState</code> variables are being evaluated too early in the page lifecycle, or that <code>EnableViewState</code> is false, but I've checked for both of these and they are as I'd expect them to be.</p>
  
  <p>My code:</p>
  
  <pre><code>public Int32 MyNumber
  {
      get
      {
          if (ViewState["MyNumber"] != null)
          {
              return (Int32)ViewState["MyNumber"];
          }
  
          return 0;
      }
      set
      {
          ViewState["MyNumber"] = value;
      }
  }
  
  protected override void OnLoad(EventArgs e)
  {
      base.OnLoad(e);
  
      if (!this.IsPostBack)
      {
          MyNumber = 23;
      }
  }
  
  protected override void OnPreRender(EventArgs e)
  {
      base.OnPreRender(e);
  
      var numberValue = MyNumber;
  }
  </code></pre>
  
  <p>When <code>OnPreRender</code> is first called, <code>numberValue</code> is 23. Every subsequent call thereafter it's 0. Every time there's a postback it appears to get reset.</p>
  
  <p><strong>Question</strong></p>
  
  <p>How do I get the value to persist after a postback?</p>
  
  <p><strong>What I've Tried</strong></p>
  
  <p>Bringing the value assignment outside of the check for a postback, but then that defeats the purpose of using <code>ViewState</code> in the first place.</p>