C# – Failed to load viewstate.The control tree into which viewstate is being loaded must match the cntrl tree that was used to save viewstate during

asp.netc

I am getting this error

"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. "

when I try to submit a page where I applied some logic on GridView rowdatabound to alter the RowSpan. On commenting this event there is no error.

here is the code :

    int firstRow;
    string previousCat;
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {

        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            var drv = e.Row.DataItem as QCParameters;

            if (previousCat == drv.AuditTypeValue)
            {
                //If it's the same category as the previous one
                //Increment the rowspan
                if (GridView1.Rows[firstRow].Cells[0].RowSpan == 0)
                {
                    GridView1.Rows[firstRow].Cells[0].RowSpan = 2;
                    GridView1.Rows[firstRow].Cells[5].RowSpan = 2;
                }
                else
                {
                    GridView1.Rows[firstRow].Cells[0].RowSpan += 1;
                    GridView1.Rows[firstRow].Cells[5].RowSpan += 1;
                }
                //Remove the cell
                if (e.Row.Cells.Count > 5)
                    e.Row.Cells.RemoveAt(5);
                e.Row.Cells.RemoveAt(0);
            }
            else //It's a new category
            {                
                e.Row.VerticalAlign = VerticalAlign.Top;
                //Maintain the category in memory
                previousCat = drv.AuditTypeValue;
                firstRow = e.Row.RowIndex;
            }
        }
   }

Best Answer

The problem is that you remove cells and than during postback (when the control tree is recreated) it does not match and the ViewState cant be loaded. One possible solution would be to "hide" the cells instead by setting: e.Row.Cells[5].Visible = false;
Not Visible controls will not be rendered but will still be part of the page control tree.