Gridview:捕获排序方向

时间:2011-02-02 02:18:40

标签: asp.net sorting gridview updatepanel sortdirection

我在updatepanel中有一个gridview,启用了排序,事件处理程序如下:

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

我在这些行之后放了一个断点。每次按下列标题时,我的变量TheDirection始终显示为Ascending。

为什么不是从上升到后退和后退?

感谢。

2 个答案:

答案 0 :(得分:2)

我一直在阅读,当您手动为gridview提供数据源时,排序似乎会中断。不确定这是不是你的情况,但这对我有用..

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();
}

希望有所帮助

答案 1 :(得分:1)

您可以在ViewState或Session中保持方向。像这样(未经测试的代码):

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;

}