2014-02-08 41 views
0

我有排序啓用一個GridView:GridView的排序問題

<asp:GridView ID="grid1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID" AllowSorting="true" OnSorting="grid1_Sorting"> 
    <Columns> 
     <asp:TemplateField HeaderText="Name" SortExpression="Name"> 
      <ItemTemplate> 
       <asp:Label ID="NameLabel" runat="server"></asp:Label> 
      </ItemTemplate> 
     </asp:TemplateField> 

然後在我的排序事件我有

VB.NET

頁面加載

Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load 
    If Not IsPostBack Then 
     ViewState("Order") = "DESC" 
    End If 
End Sub 

    Protected Sub grid1_Sorting(sender As Object, e As GridViewSortEventArgs) Handles grid1.Sorting 
Select Case e.SortExpression 
      Case "Name" 
       If ViewState("Order") = "DESC" Then 
        grid1.DataSource = DescData() 
        grid1.DataBind() 
        ViewState("Order") = "ASC" 
        Exit Select 
       Else 
        grid1.DataSource = AscData() 
        grid1.DataBind() 
        ViewState("SortOrder") = "DESC" 
        Exit Select 
       End If 
End Select 

C#

protected void grid1_Sorting(object sender, GridViewSortEventArgs e) 
{ 
    switch (e.SortExpression) { 
     case "Name": 
      if (e.SortDirection == SortDirection.Ascending) { 
       grid1.DataSource = AscendingData(); 
       grid1.DataBind(); 
       e.SortDirection = SortDirection.Descending; 
       break; 
      } else { 
       grid1.DataSource = DescendingData(); 
       grid1.DataBind(); 
       e.SortDirection = SortDirection.Ascending; 
       break; 
      } 
      break; 
    } 
} 

我讀過很多文章,但大多數人似乎針對一個DataTable或使用視圖狀態。這給我的印象我錯過了一些東西,以獲得上述工作。

我遇到的問題是,當我單擊列進行排序時,如果條件(即升序然後降序代碼)通過,但我不明白爲什麼?

+0

已知問題http://stackoverflow.com/questions/250037/gridview-sorting-sortdirection-always-ascending – Sachin

+0

我讀過,但正如我在我的文章中提到它目標datatable或使用Viewstate。你是否建議這是實現這一點的正確方法(在這種情況下使用Viewstate)? – Computer

+0

是的,你可以使用viewstate來解決這個問題。 – Sachin

回答

0

好的問題出現在aspx頁面。 gridview有OnSorting =「grid1_Sorting」。刪除這條線解決了它。

我想我必須複製一些C#代碼並添加該行代碼。刪除該行解決了問題,因爲它導致GV分類兩次。