编辑详细记录后,在gridview中选择了错误的记录

时间:2016-03-31 16:08:32

标签: asp.net gridview detailsview

我有一个GridView显示几条记录。单击说出第三条记录,在下面显示一个DetailsView,我可以在其中编辑记录。如果我对记录进行更改并保存,则GridView会刷新并重新排序,现在我编辑的记录是第5行。但是,仍然选择第3行,DetailsView现在显示的记录与我刚刚编辑的记录不同。

通过DetailsView进行更新后,如何确保在GridView中重新选择THAT记录,无论它现在在GridView排序顺序中的哪个位置?

1 个答案:

答案 0 :(得分:0)

您可以通过将字段添加到GridView的DataKeyNames来跟踪每行的ID。在代码隐藏中刷新网格之前,您需要记住所选行的ID(假设相关ID是名为ClientID的字段):

int savedClientID = (int)gvClients.DataKeys[gvClients.SelectedIndex].Values["ClientID"];

然后,您可以在绑定数据后查找它并选择相应的行:

void gvClients_DataBound(object sender, EventArgs e)
{
    gvClients.SelectedIndex = -1;

    foreach (GridViewRow row in gvClients.Rows)
    {
        int clientID = (int)gvClients.DataKeys[row.RowIndex].Values["ClientID"];

        if (clientID == savedClientID)
        {
            gvClients.SelectedIndex = row.RowIndex;
            break;
        }
    }
}

<强>更新

如果在GridView中启用了分页,则可能必须使用此帖子中建议的方法:GridView in ASP.Net -- Selecting the correct row