0

我应该怎么做才能在网格视图中执行排序?

请帮忙

4

2 回答 2

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>
于 2010-02-27T06:53:30.800 回答
0

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

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

< 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

}
于 2010-02-27T06:31:58.290 回答