Asp.net

GridView 排序:SortDirection 總是升序

  • October 30, 2008

我有一個gridview,當使用者點擊標題時,我需要對其元素進行排序。

它的數據源是一個 List 對象。

aspx 是這樣定義的:

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

後面的程式碼是這樣定義的:

首先載入:

protected void btnSearch_Click(object sender, EventArgs e)
{
   List<V_ReportPeriodStatusEntity> items = GetPeriodStatusesForScreenSelection();
   this.grdHeader.DataSource = items;
   this.grdHeader.DataBind();
}

當使用者點擊標題時:

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

我的問題是 e.SortDirection 總是設置為升序。

我有一個類似程式碼的網頁,它執行良好,e.SortDirection 在升序和降序之間交替。

我做錯了什麼 ?

您可以使用會話變數來儲存最新的排序表達式,並在下次對網格進行排序時將網格的排序表達式與儲存上次排序表達式的會話變數進行比較。如果列相等,則檢查先前排序的方向並按相反方向排序。

例子:

DataTable sourceTable = GridAttendence.DataSource as DataTable;
DataView view = new DataView(sourceTable);
string[] sortData = ViewState["sortExpression"].ToString().Trim().Split(' ');
if (e.SortExpression == sortData[0])
{
   if (sortData[1] == "ASC")
   {
       view.Sort = e.SortExpression + " " + "DESC";
       this.ViewState["sortExpression"] = e.SortExpression + " " + "DESC";
   }
   else
   {
       view.Sort = e.SortExpression + " " + "ASC";
       this.ViewState["sortExpression"] = e.SortExpression + " " + "ASC";
   }
}
else
{
   view.Sort = e.SortExpression + " " + "ASC";
   this.ViewState["sortExpression"] = e.SortExpression + " " + "ASC";
}

Session 和 Viewstate 的問題在於,如果頁面上有多個 gridview,您還必須跟踪儲存 SortColumn 和 Direction 的 gridview 控制項。

Session 和 Viewstate 的替代方法是將 2 個屬性添加到 Gridview 並以這種方式跟踪 Column 和 Direction。

這是一個例子:

private void GridViewSortDirection(GridView g, GridViewSortEventArgs e, out SortDirection d, out string f)
{
   f = e.SortExpression;
   d = e.SortDirection;

   //Check if GridView control has required Attributes
   if (g.Attributes["CurrentSortField"] != null && g.Attributes["CurrentSortDir"] != null)
   {
       if (f == g.Attributes["CurrentSortField"])
       {
           d = SortDirection.Descending;
           if (g.Attributes["CurrentSortDir"] == "ASC")
           {
               d = SortDirection.Ascending;
           }
       }

       g.Attributes["CurrentSortField"] = f;
       g.Attributes["CurrentSortDir"] = (d == SortDirection.Ascending ? "DESC" : "ASC");
   }

}

引用自:https://stackoverflow.com/questions/250037