如何使用自动生成的列对gridview进行排序?

时间:2014-04-03 03:23:36

标签: asp.net vb.net gridview-sorting

我有一个自动生成列false的gridview。我想点击每个列标题对gridview进行排序。我的代码适用于autogenerate列true但我希望它是真的。

我的代码:

Protected Sub grdWork_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles grdPWork.Sorting

    If ViewState("SortDirection") = SortDirection.Ascending Then
        ViewState("SortDirection") = SortDirection.Descending
        SortTrackingGrid(e.SortExpression, " Desc")
    Else
        ViewState("SortDirection") = SortDirection.Ascending
        SortTrackingGrid(e.SortExpression, " Asc")
    End If
End Sub

Private Sub SortTrackingGrid(ByVal SortExpression As String, ByVal SortDirection As String)

    Dim TrackingDt As New DataTable

    TrackingDt = objWebService.BindPWork()

    Dim Trackingdv As New DataView
    Trackingdv = TrackingDt.DefaultView

    'Sort the grid
    Trackingdv.Sort = SortExpression + SortDirection
    grdPWork.DataSource = Trackingdv
    grdPWork.DataBind()


End Sub

1 个答案:

答案 0 :(得分:0)

以下是使用autogenerate column false对网格视图进行排序的完整示例。

http://www.dotnetgallery.com/kb/resource12-How-to-implement-paging-and-sorting-in-aspnet-Gridview-control.aspx

基本上你需要在GridView排序事件中使用SortExpression。

protected void Sorting(object sender, GridViewSortEventArgs e)
    {
        string[] SortOrder = ViewState["SortExpr"].ToString().Split(' ');
        if (SortOrder[0] == e.SortExpression)
        {
            if (SortOrder[1] == "ASC")
            {
                ViewState["SortExpr"] = e.SortExpression + " " + "DESC";
            }
            else
            {
                ViewState["SortExpr"] = e.SortExpression + " " + "ASC";
            }
        }
        else
        {
            ViewState["SortExpr"] = e.SortExpression + " " + "ASC";
        }
        GridVwPagingSorting.DataSource = Getdata();
        GridVwPagingSorting.DataBind();
    }