Gridview: capturing sort direction

怎甘沉沦 提交于 2019-12-11 05:35:12

问题


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.


回答1:


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;

}



回答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



来源:https://stackoverflow.com/questions/4870163/gridview-capturing-sort-direction

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!