Reputation: 10565
I set the sort expression for a column in a grid view. Then sort the column by clicking on Header. Upto this point fine.
However, when I select a gridView row using the select button which is autogenerated:
<asp:GridView runat="server" ID="test" DataSourceID="sourceEmployees"
AutoGenerateSelectButton="true">
After selecting a row if I sort the Column by clicking on Header, the GridView still has the old row selected. The intially selected value is lost. If i Select employeeID value 7, the 7th row remains selected even when I sort the Column in descending order, Although my employeeId value 7 has moved to different row. [ here its moved to 4th row as I have total 10 employees ]
What more I need to implement to make sure No matter the way user sorts the GridView, always the initially selected employeeID remains selected.
Upvotes: 2
Views: 586
Reputation: 10565
We need to use the GridView.EnablePersistedSelection
Property. MSDN states that
If this property is false and a row is selected, the same row is selected when a new page is displayed even though the new page has different data in it. If you set this property to true, when you display a page that has different data in it, no row is selected. If you then return to the page on which a row was selected, that row is still selected.
Setting this property to true
resolved my issue.
Upvotes: 3
Reputation: 63966
You need to handle everything on the code behind (selecting/deselecting the row when the index changes). Here's an example based on your set up:
<asp:GridView DataKeyNames="EmpID"
SelectedRowStyle-BackColor="Yellow" ID="test" OnSelectedIndexChanged="test_SelectedIndexChanged"
runat="server" DataSourceID="sourceEmployees" AutoGenerateColumns="False"
AutoGenerateSelectButton="true" AllowSorting="true"
OnRowDataBound="test_RowDataBound" >
Above, I added two event handlers, one for OnRowDataBound
and one for OnSelectedIndexChanged
. I also added the DataKey
to keep track of the selected employee ID.
Now, on code behind, the for those 2 methods looks like this:
protected void test_SelectedIndexChanged(object sender, EventArgs e)
{
ViewState["key"]= test.SelectedDataKey.Value;//Keep track of selected employee by ID
}
protected void test_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var row = e.Row.DataItem as DataRowView;
if (row.Row.Field<int>("EmpID") == (ViewState["key"] != null ? (int)ViewState["key"] : -1))
{
test.SelectedIndex = e.Row.RowIndex;
//Setting the selected Index is not enough, you need to programmatically
//set the color as well. Since I used Yellow on my markup, I use the same here
e.Row.BackColor = System.Drawing.Color.Yellow;
}
}
}
Upvotes: 3