代码之家  ›  专栏  ›  技术社区  ›  MAW74656

在c#.net中对绑定到datatable的gridview进行排序

  •  3
  • MAW74656  · 技术社区  · 16 年前

    我有一个绑定到DataTable的gridview。当我尝试对gridview进行排序时,它变为空白。如何对这个gridview进行排序?

    我知道以前有人问过这个问题,但我要找的是 解释

    再说一次,我想了解实现这一点的方法,我不只是想要一个巨大的代码块。


                <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>
    

    然后在代码隐藏中:

      //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;
    

    2 回复  |  直到 15 年前
        1
  •  1
  •   hav2play21    16 年前

    您可以使用DataTable使GridView可排序。您需要做的就是确保启用Sorting=true,并提供希望在SortExpression中排序的列名。

    您需要这样做才能使其可排序:

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

    您总是需要设置SortExpression,否则您将无法对列进行排序

        2
  •  1
  •   anishMarokey FIre Panda    16 年前

    请看一下GridView的例子ASP.NET2.0: Paging and Sorting the GridView's Data

    推荐文章