I have a gridview and I need to sort its elements when the user clicks on the header.
Its datasource is a List object.
The aspx is defined this way :
<asp:GridView ID='grdHeader' AllowSorting='true' AllowPaging='false' AutoGenerateColumns='false' Width='780' runat='server' OnSorting='grdHeader_OnSorting' EnableViewState='true'> <Columns> <asp:BoundField DataField='Entitycode' HeaderText='Entity' SortExpression='Entitycode' /> <asp:BoundField DataField='Statusname' HeaderText='Status' SortExpression='Statusname' /> <asp:BoundField DataField='Username' HeaderText='User' SortExpression='Username' /> </Columns> </asp:GridView>
The code behind is defined this way :
First load :
protected void btnSearch_Click(object sender, EventArgs e) { List<V_ReportPeriodStatusEntity> items = GetPeriodStatusesForScreenSelection(); this.grdHeader.DataSource = items; this.grdHeader.DataBind(); }
when the user clicks on headers :
protected void grdHeader_OnSorting(object sender, GridViewSortEventArgs e) { List<V_ReportPeriodStatusEntity> items = GetPeriodStatusesForScreenSelection(); items.Sort(new Helpers.GenericComparer<V_ReportPeriodStatusEntity>(e.SortExpression, e.SortDirection)); grdHeader.DataSource = items; grdHeader.DataBind(); }
My problem is that e.SortDirection is always set to Ascending.
I have webpage with a similar code and it works well, e.SortDirection alternates between Ascending and Descending.
What did I do wrong ?
You can use a session variable to store the latest Sort Expression and when you sort the grid next time compare the sort expression of the grid with the Session variable which stores last sort expression. If the columns are equal then check the direction of the previous sort and sort in the opposite direction.
Example: