2013-05-07 61 views
2

其Arun。這次我在ASP.Net中有一個排序問題。對於第一次點擊,降序工作正常,但在第二次點擊升序不再採取。它仍然以降序排列。我使用Tableadapter來顯示gridview內容。請檢查代碼並將我改正到我錯過的地方。在ASP.NET Gridview中排序

protected void gv1_Sorting(object sender, GridViewSortEventArgs e) 
    { 
     string sdir = e.SortDirection == SortDirection.Ascending ? "DESC" : "ASC"; 
     DataView dv = new DataView(ds2.AllocationPending(ClientLoggedIn.Text)); 
     dv.Sort = e.SortExpression + " " + sdir; 
     gv1.DataSource = dv; 
     gv1.DataBind(); 
    } 

也請解釋 - 是否有任何其他方式來應用沒有Dataview的排序。

謝謝。

回答

2

我已經找到了這個問題的解決方案。原因是e.SortDirection總是返回Ascending。所以我需要將e.SortDirection存儲在ViewState中,並使用該值對數據視圖進行排序。更新編碼如下:

protected void gv1_Sorting(object sender, GridViewSortEventArgs e) 
    { 
     string SortDirection = "DESC"; 
     if (ViewState["SortExpression"] != null) 
     { 
      if (ViewState["SortExpression"].ToString() == e.SortExpression) 
      { 
       ViewState["SortExpression"] = null; 
       SortDirection = "ASC"; 
      } 
      else 
      { 
       ViewState["SortExpression"] = e.SortExpression; 
      } 
     } 
     else 
     { 
      ViewState["SortExpression"] = e.SortExpression; 
     } 

     DataView dv = new DataView(ds2.AllocationPending(ClientLoggedIn.Text)); 
     dv.Sort = e.SortExpression + " " + SortDirection; 
     gv1.DataSource = dv; 
     gv1.DataBind(); 
    } 
+0

我不明白爲什麼e.SortDirection被使用然後...微軟實際上說,它應該自動改變,如果你點擊兩次相同的列標題... – 2018-01-24 14:01:34

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

     if (dtSortTable != null) 
     { 
      DataView dvSortedView = new DataView(dtSortTable); 

      dvSortedView.Sort = e.SortExpression + "" + getSortDirectionString(e.SortDirection); 

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

private string getSortDirectionString(SortDirection sortDirection) 
    { 
     string newSortDirection = String.Empty; 
     if(sortDirection== SortDirection.Ascending) 
     { 
      newSortDirection = "DESC"; 
     } 
     else 
     { 
      newSortDirection = "ASC"; 
     } 
     return newSortDirection; 
} 

試試這個代碼排序的GridView控件

+0

我不是使用radgrid控件。我正在開發ASP.Net Gridview。以上代碼僅適用於Radgrid。所以對我來說沒有用處。 – Aruna 2013-05-07 10:46:19

+0

@ArunachalamGurusamy:現在試試這個....... – 2013-05-07 10:54:41

+0

謝謝Chetan的GridView代碼。但是它與我在我的問題中發佈的代碼邏輯相同。你把Sortdirection作爲一個單獨的函數來調用,而我將它包含在同一個函數中。如果(sortDirection == SortDirection.Ascending)then newSortDirection =「DESC」;無論如何,它的工作罰款第一次,但不是第二次。請看看。 – Aruna 2013-05-07 11:11:13