简体   繁体   English

在GridView + Asp.net中排序

[英]Sorting in GridView + Asp.net

What should I do to perform the sorting in grid view? 如何在网格视图中执行排序?

Please help 请帮忙

You can implement code like the following: 您可以实现如下代码:

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

With this code, your GridView definition should read: 使用此代码,您的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>

Not sure if you have already added the event or not in your code behind. 不知道您是否已经在后面的代码中添加了事件。

You have AllowSorting="true" set for the GridView and therefore you need to have event handler for its Sorting event. 您为GridView设置了AllowSorting="true" ,因此需要为其Sorting事件设置事件处理程序。

< 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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM