Gridview Automatically Selects first Row after a sort
asp.net, c#, gridview, sorting
Solution
Here you need to use the `GridView.EnablePersistedSelection` property. Set this property to `true`.
Setting this property to `true` means that `GridView` will make sure that the selection of a row is based on data-key values.
By default GridView makes row selections based on index. This is the reason why when you sort, gridview is selecting row based on index and you lose your actual selected row.
Problem
I am working on a master/detail gridview and detailsview in asp.net web forms using an objectdatasource. The details view is displaying extra information about the selected row from the gridview. When I sort the grid, I want the currently selected row, before sort occurs, to remain in the details view after the sort is completed. Instead, the gridview is auto selecting the new first row whenever I sort. I found a partial solution to this problem. If I set WhateverGridview.SelectedIndex= -1 onsort and the value becomes null. This makes it deselect any rows after a sort. This leaves the details view blank. However, what I want to do is maintain the selected row not nullify it. So, does anyone have a good way to retain the selected value or prevent the details view from displaying after sort event fires.