allow sorting by column gridview

后端 未结 2 644
说谎
说谎 2020-12-19 16:41

I am writing project which gets data from Data Acess Layer and show it in GridView. The problem is to allow sorting by column. When I click on head of columnt following occu

相关标签:
2条回答
  • 2020-12-19 17:12

    The GridView does not sort itself. You need to add some code for a GridView sorting event and wire it up.

    First, you add the name of the OnSorting event to the GridView on the .aspx page:

    <asp:GridView ID="gridView" OnSorting="gridView_Sorting" runat="server" />
    

    Then, you add that event in the code-behind. This example also handles changing the sort direction -- once the user has sorted, they may want to reverse the sort direction, and you have to keep track of that.

       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;
    }
    
    protected void gridView_Sorting(object sender, GridViewSortEventArgs e)
    {
       DataTable dataTable = gridView.DataSource as DataTable;
    
       if (dataTable != null)
       {
          DataView dataView = new DataView(dataTable);
          dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
    
          gridView.DataSource = dataView;
          gridView.DataBind();
       }
    }
    
    0 讨论(0)
  • 2020-12-19 17:19

    You need to define a sort melhod, and implement it:

    <asp:GridView ID="GridView1" **OnSorting="gridViewSorting"** runat="server" />
    
    
    
    protected void gridViewSorting(object sender, GridViewSortEventArgs e)
    {
       DataTable dataTable = gridView.DataSource as DataTable;
    
       if (dataTable != null)
       {
          DataView dataView = new DataView(dataTable);
          dataView.Sort = your sort expression
    
          gridView.DataSource = dataView;
          gridView.DataBind();
       }
    }
    
    0 讨论(0)
提交回复
热议问题