1

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.

akjoshi
  • 14,989
  • 13
  • 101
  • 119
frenchie
  • 48,391
  • 102
  • 295
  • 498

2 Answers2

2

I've been reading and the sorting seems to break when you are manually providing the gridview a datasource. Not sure if that is your case, but this works for me..

string strSortExpression = e.SortExpression + " ASC";
if (Convert.ToString(ViewState["SortExpression"]) == strSortExpression)
{
    strSortExpression = e.SortExpression + " DESC";
}
ViewState["SortExpression"] = strSortExpression;


//This is done by sorting the Default View of the underlying data and then re-binding this
//to the grid.
System.Data.DataTable myData = HttpContext.Current.Session["GridData"] as System.Data.DataTable;
if (myData != null)
{
   myData.DefaultView.Sort = strSortExpression;
   GridView1.DataSource = myData;
   GridView1.DataBind();
}

hope it helps

Sotiris
  • 37,572
  • 11
  • 48
  • 84
Bill
  • 21
  • 3
0

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;

}
Victor
  • 4,683
  • 1
  • 24
  • 31
  • 1
    No need to use a Session variable or view state variable, you can store it directly in the GridView's `SortDirection` and `SortExpression` properties. – Scott Mitchell Feb 02 '11 at 03:08