GridView排序问题

我有一个现有的gridview,我需要在工作中修复/改进。 基本上GridView有标题,它们被后面代码中的数据集绑定,它使用BoundFields和TemplateFields。 问题是我需要让每个列都可以排序。 这样做的最佳方法是什么,因为它不是标准的gridview?,我需要制作标题链接,然后单击以DESC或ASC顺序排序。 这是我需要处理的gridview的一个例子。

     <a href='https://stackoverflow.com/questions/6602015/gridview-sorting-question/sometest.aspx?ID='>     

…等,对BoundFields和TemplateFields进行排序的最佳方法是什么?

您需要设置SortExpression 。

   <%# DataBinder.Eval(Container.DataItem, "Type").ToString()%>     
<%# (DataBinder.Eval(Container.DataItem, "HouseNumber"))%>

在代码隐藏中,您可以在ViewState中存储当前的SortExpression和SortDirection:

 Private Property SortExpression() As String Get If ViewState("SortExpression") Is Nothing OrElse ViewState("SortExpression").ToString().Length = 0 Then ViewState("SortExpression") = "Name ASC" End If Return ViewState("SortExpression").ToString End Get Set(ByVal value As String) ViewState("SortExpression") = value End Set End Property 

在GridView的Sorting-Handler中:

 Protected Sub theGrid_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles theGrid.Sorting Dim currentSortColumn, currentSortDirection As String currentSortColumn = Me.SortExpression.Split(" "c)(0) currentSortDirection = Me.SortExpression.Split(" "c)(1) If e.SortExpression.Equals(currentSortColumn) Then 'switch sort direction Select Case currentSortDirection.ToUpper Case "ASC" Me.SortExpression = currentSortColumn & " DESC" Case "DESC" Me.SortExpression = currentSortColumn & " ASC" End Select Else Me.SortExpression = e.SortExpression & " ASC" End If BindGrid() 'load the data with this SortExpression and DataBind the Grid' End Sub 

对不起VB.NET,我注意到太晚了。 你可以在这里翻译它。

编辑:C#

 private string SortExpression { get { if (ViewState("SortExpression") == null || ViewState("SortExpression").ToString().Length == 0) { ViewState("SortExpression") = "Name ASC"; } return ViewState("SortExpression").ToString; } set { ViewState("SortExpression") = value; } } protected void theGrid_Sorting(object sender, System.Web.UI.WebControls.GridViewSortEventArgs e) { string currentSortColumn = null; string currentSortDirection = null; currentSortColumn = this.SortExpression.Split(' ')[0]; currentSortDirection = this.SortExpression.Split(' ')[1]; if (e.SortExpression.Equals(currentSortColumn)) { //switch sort direction switch (currentSortDirection.ToUpper()) { case "ASC": this.SortExpression = currentSortColumn + " DESC"; break; case "DESC": this.SortExpression = currentSortColumn + " ASC"; break; } } else { this.SortExpression = e.SortExpression + " ASC"; } //load the data with this SortExpression and DataBind the Grid BindGrid(); }