Search code examples
asp.netgridviewviewstatefailed-to-load-viewstate

GridView Changing EditIndex on RowEditing then Cancelling Edit yields in ViewState Error


I have a DataSet1 which has 4 rows which I bind to GridView1.
GridView1 has an Edit (image) command.
When a user clicks on row 1, in the RowEditing event, I will remove a particular row (row 0) in DataSet1 and update GridView1.
EditIndex to 0 and rebind DataSet1 to GridView1.

GridView1.EditIndex = 0;
GridView1.DataSource = DataSet1;
GridView1DataBind();

The problem appears when the user cancels editing. I am getting the 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.

It appears to be because of the mismatch in the original EditIndex (row 1) and the new EditIndex which I set (row 0).


Solution

  • I found the solution. The mismatch in ViewState is because while GridView1.EditIndex was updated, the event argument field e.NewEditIndex value (which I'm guessing is updating the ViewState) is not updated. See updated code below that works:

    GridView1.EditIndex = 0;
    e.NewEditIndex = 0;
    GridView1.DataSource = DataSet1;
    GridView1DataBind();