Gridview sort bound to datatable in C # .net

I have a gridview bound to a DataTable. When I try to sort the gridview, it becomes empty. How to enable sorting of this gridview?

I know this question has been asked before, but what I'm looking for is an explanation of how to do this. Perhaps with a simple example.

I read that I need to put some code in on_sorting and / or on_sorted events, but I don’t understand that I need to go there.

Again, I want to understand a way to accomplish this, I don't just want a giant block of code.


Ok, here's what I have now, but still not working:

            <asp:GridView ID="gridResults" runat="server" CellPadding="4" ForeColor="#333333"
            GridLines="Horizontal" AllowSorting="True" AllowPaging="True" 
            EmptyDataText="No Tracking Information Found for the given criteria." 
            PageSize="15" onsorted="gridResults_Sorted" AutoGenerateColumns="False" 
            EnableSortingAndPagingCallbacks="True">
            <RowStyle BackColor="#E3EAEB" />
            <FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
            <HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
            <EditRowStyle BackColor="#7C6F57" />
            <AlternatingRowStyle BackColor="White" />
        </asp:GridView>

And then in the code behind:

  //From search method
gridResults.Columns.Clear();
    foreach (DataColumn col in currentResults.Columns)
    {
        String fieldName = col.ColumnName;
        BoundField field = new BoundField();
        field.DataField = fieldName;
        field.SortExpression = fieldName;
        field.HeaderText = fieldName;

        gridResults.Columns.Add(field);  
    }

    gridResults.DataSource = currentResults;
    gridResults.DataBind();
    gridResults.AllowSorting = true;

Can anyone see what I still don't see? The results show, but no sorting or swapping is performed.

+3
2

GridView DataTable. , , , Enable Sorting = true, , SortExpression.

, , :

<asp:BoundField HeaderText="Product" 
      DataField="ProductName" SortExpression="ProductName">
</asp:BoundField>

SortExpression

+1

, GridView ASP.NET 2.0: GridView

+1

Source: https://habr.com/ru/post/1766991/


All Articles