title: ASP Gridview Failed to load viewstate.
body: <p>I am getting an error in asp.net 4.5 when i dynamically create a button in <code>GridView.ROWDATABOUND</code> event.</p>
  
  <p>code for button:</p>
  
  <pre><code>Dim btn1 As New Button()
  btn1.ID = "btn1"
  btn1.Width = "50"
  btn1.Text = "Edit"
  btn1.CssClass = "AdminPageBtn"
  btn1.CommandName = "Edit"
  btn1.CommandArgument = "Edit"
  btn1.Enabled = True
  </code></pre>
  
  <p>e.Row.Cells(e.Row.Cells.Count - 1).Controls.Add(btn1)</p>
  
  <p>And I'm using AJAX 4.0 too, with script manager and update panel.</p>
  
  <p>that button execute the below method</p>
  
  <pre><code>Protected Sub gvwRoutes_RowEditing(ByVal sender As Object, 
                        ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs)
                  Handles gvwRoutes.RowEditing
  End Sub
  </code></pre>
  
  <p>when it is executed, there is an error:</p>
  
  <p><code>Failed to load viewstate.  The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during the previous request.  For example, when adding controls dynamically, the controls added during a post-back must match the type and position of the controls added during the initial request.</code></p>
  
  <p>Need a Solution..!</p>