【问题标题】:Sorting in GridView + Asp.net在 GridView + Asp.net 中排序
【发布时间】:2011-01-21 17:34:53
【问题描述】:

如何在网格视图中执行排序?

请帮忙

【问题讨论】:

    标签: c# asp.net gridview gridview-sorting


    【解决方案1】:

    您可以实现如下代码:

    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
         DataTable dataTable = GridView1.DataSource as DataTable;
    
         if (dataTable != null)
         {
              DataView dataView = new DataView(dataTable);
              dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
    
              GridView1.DataSource = dataView;
              GridView1.DataBind();
         }
    }
    
    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;
    }
    

    使用此代码,您的 GridView 定义应为:

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" AllowSorting="true" OnSorting="GridView1_Sorting">
    <Columns>
        <asp:BoundField DataField="Name" HeaderText="People Names" SortExpression="Name" />
        <asp:BoundField DataField="Age" HeaderText="People Ages" SortExpression="Age" />
    </Columns>
    </asp:GridView>
    

    【讨论】:

    【解决方案2】:

    不确定您是否已经在后面的代码中添加了事件。

    您为 GridView 设置了 AllowSorting="true",因此您需要 为其排序事件提供事件处理程序。

    < asp:GridView AllowSorting=true ID="GridView1" runat="server" 
      OnSorting="GridView1_Sorting" >
        ...
    < /asp:GridView >
    
    
    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    
    {
    
         //Add your code here for handling
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      • 2016-07-31
      • 1970-01-01
      • 2017-03-28
      • 2011-09-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多