在GridView + Asp.net中排序

时间:2010-02-27 06:26:40

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

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

请帮忙

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分:0)

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

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

}