Search code examples
asp.netsortinggridviewupdatepanelsortdirection

Gridview: capturing sort direction


I have a gridview in an updatepanel with sorting enabled and an event handler as follows:

protected void MyGridSort(object sender, GridViewSortEventArgs e)
{
   var TheDirection = (e.SortDirection).ToString();
   var TheColumn = (e.SortExpression).ToString();
}

I put a breakpoint just after these lines. Every time I press the column header, my variable TheDirection is always showing Ascending.

Why is it not toggling from ascending to descending and back?

Thanks.


Solution

  • You could keep the direction in the ViewState or the Session. Like this (Untested Code):

    protected void MyGridSort(object sender, GridViewSortEventArgs e)
    {
       var TheDirection = (e.SortDirection).ToString();
       var TheColumn = (e.SortExpression).ToString();
    
       string prevColumn = "", prevDirection = "";
    
       if (Session["MyGridSortColumn"] != null)
          prevColumn = Session["MyGridSortColumn"].ToString();
       if (Session["MyGridSortDirection"] != null)
          prevDirection = Session["MyGridSortDirection"].ToString();
    
       if (TheColumn == prevColumn) {
          if (prevDirection == "ASC")
             TheDirection = "DESC";
          else
             TheDirection = "ASC";
       }
    
       Session["MyGridSortDirection"] = TheDirection;
       Session["MyGridSortColumn"] = TheColumn;
    
    }