2010-02-27 73 views

回答

1

您可以實現類似下面的代碼:

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e) 
{ 
    DataTable dataTable = GridView1.DataSource as DataTable; 

    if (dataTable != null) 
    { 
      DataView dataView = new DataView(dataTable); 
      dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection); 

      GridView1.DataSource = dataView; 
      GridView1.DataBind(); 
    } 
} 

private string ConvertSortDirectionToSql(SortDirection sortDirection) 
{ 
    string newSortDirection = String.Empty; 

    switch (sortDirection) 
    { 
      case SortDirection.Ascending: 
       newSortDirection = "ASC"; 
      break; 

      case SortDirection.Descending: 
       newSortDirection = "DESC"; 
      break; 
    } 

    return newSortDirection; 
} 

有了這個代碼,你的GridView的定義應爲:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" AllowSorting="true" OnSorting="GridView1_Sorting"> 
<Columns> 
    <asp:BoundField DataField="Name" HeaderText="People Names" SortExpression="Name" /> 
    <asp:BoundField DataField="Age" HeaderText="People Ages" SortExpression="Age" /> 
</Columns> 
</asp:GridView> 
+0

嘗試在同一列再次點擊,看看它是否在其他方向排序。 – 2010-02-27 07:19:20

+1

您的問題可以通過以下鏈接解決: http://stackoverflow.com/questions/250037/gridview-sorting-sortdirection-always-ascending – 2010-02-27 07:36:03

0

不知道你是否已經在你的代碼中添加了事件或不在你身後。

您有爲GridView設置的AllowSorting="true",因此您需要 爲其排序事件設置了事件處理程序。

< asp:GridView AllowSorting=true ID="GridView1" runat="server" 
    OnSorting="GridView1_Sorting" > 
    ... 
</asp:GridView> 


protected void GridView1_Sorting(object sender, GridViewSortEventArgs e) 

{ 

    //Add your code here for handling 

}