GridView在RowEditing上更改EditIndex,然后在ViewState错误中取消编辑产生

时间:2013-05-27 04:47:06

标签: asp.net gridview viewstate failed-to-load-viewstate

我有一个DataSet1,其中4 rowsGridView1绑定 GridView1有一个Edit (image) command 当用户点击第1行时,在RowEditing event中,我会删除DataSet1中的特定行(第0行)并更新GridView1
EditIndex为0并将DataSet1重新绑定到GridView1

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

用户取消编辑时出现问题。我收到了错误:

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.  

例如,在动态添加控件时,回发期间添加的控件必须与初始请求期间添加的控件的类型和位置相匹配。

这似乎是因为原始EditIndex(第1行)和我设置的新EditIndex(第0行)不匹配。

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。 ViewState中的不匹配是因为更新了GridView1.EditIndex时,事件参数字段e.NewEditIndex值(我猜测它正在更新ViewState)不会更新。请参阅下面有效的更新代码:

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