title: ViewState["sample"] Variable not retaining value on postback in a composite control
body: <p>I have created a composite control with sample details as follows. Basically, the first time on page load the control sets a view state variable and the problem is that on post back (when the button is clicked), the ViewState variable is null. I have researched extensively and I am not able to find a solution. I checked all the Microsoft recommended articles and also from other developers. This approach seem to work for everyone and I can't figure out what I'm doing wrong. If anyone can help, I would really appreciate it.</p>
  
  <p>PS: This code may not work as it is only for illustrative purposes. but this is exactly what i'm doing in my code.</p>
  
  <pre><code>Public class Test : CompositeControl
  {
      private Button btnTest = new Button();
      public string TestViewState
      {
          get
          {
              string s = (string)ViewState["test"];
              return (s == null) ? String.Empty : s;
          }
          set
          {
              ViewState["test"] = value;
          }
      }
  
      private void set()
      {
          TestViewState = "test";
      }
  
      protected void Page_Load(object sender, EventArgs e)
      {  
          if(!Page.IsPostBack)
              set();  
      }
  
      protected override void RecreateChildControls()
      {
          EnsureChildControls();
      }
  
      protected override void CreateChildControls()
      {
           base.Controls.Clear();  
           btnTest.ID = "btnTest";
           btnTest.Click += new EventHandler(btnSubmitTest_Click);
  
           if (!ChildControlsCreated)
           Controls.Add(btnTest);      
  
          base.CreateChildControls();
      }
  
      protected override void Render(HtmlTextWriter writer)
      {
          btnSumbit.Render(writer);
      }
  
      protected void btnSubmitTest_Click(object sender, EventArgs e)
      {
          string test = TestViewState; // Viewstate value is null here!!!!!!
      }
  }
  </code></pre>