允许按列gridview排序

我正在编写从Data Acess Layer获取数据并在GridView中显示它的项目。 问题是允许按列排序。 当我点击columnt后面的头部发生以下错误:

exception详细信息:System.Web.HttpException:GridView’GridView1’触发事件排序,尚未处理。

这里的.cs代码:

public partial class Default: System.Web.UI.Page { EmployeesTableAdapter eta = new EmployeesTableAdapter(); protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { GridView1.DataSource = eta.GetData(); GridView1.DataBind(); } } } 

这里是.aspx代码(仅限gridview):

                                   

someony知道如何允许按列排序吗?

GridView不对自身进行排序。 您需要为GridView排序事件添加一些代码并将其连接起来

首先,将OnSorting事件的名称添加到.aspx页面上的GridView

  

然后,在代码隐藏中添加该事件。 此示例还处理更改排序方向 – 一旦用户排序,他们可能想要反转排序方向,您必须跟踪它。

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

您需要定义一个排序方法,并实现它:

  protected void gridViewSorting(object sender, GridViewSortEventArgs e) { DataTable dataTable = gridView.DataSource as DataTable; if (dataTable != null) { DataView dataView = new DataView(dataTable); dataView.Sort = your sort expression gridView.DataSource = dataView; gridView.DataBind(); } } 

为什么你们都要重新发明轮子并编写代码来处理排序,当你需要做的就是这个?

 AllowSorting="True"