简体   繁体   English

如何在asp.net中的GridView中对数据进行排序

[英]How to sort data in GridView in asp.net

How to sort datatable obtained by GridView according to some column. 如何根据某些列对GridView获取的数据表进行排序。 I am trying to do something like this but it is not working. 我试图做这样的事情,但它不起作用。

protected void GridView_Sorting(object sender, GridViewSortEventArgs e)
{
    if (sender.GetType() != typeof(GridView))
        return;
    DataTable dt = (DataTable)((GridView)sender).DataSource;

    DataTable dtClone = dt.Clone();


    dt.AsEnumerable().OrderBy(row => row.Field <string>(e.SortExpression));
    ((GridView)sender).Source(dtClone);
}

You can either re-bind the gridview to the sorted datatable, or you can apply the sort expression to the gridview itself rather than the underlying bound table. 您可以将gridview重新绑定到已排序的数据表,也可以将sort表达式应用于gridview本身而不是底层绑定表。

This is a pretty good summary with links to examples: 这是一个非常好的摘要,带有示例链接:

http://msdn.microsoft.com/en-us/library/hwf94875.aspx http://msdn.microsoft.com/en-us/library/hwf94875.aspx

Add the attributes OnSorting="gridView_Sorting" AllowSorting="true" in Gridview 在Gridview中添加属性OnSorting="gridView_Sorting" AllowSorting="true"

and SortExpression="ColumnName" in the column 列中的SortExpression="ColumnName"

and implement OnSorting Event. 并实现OnSorting事件。

check the links 检查链接

Sorting the GridView's Data 对GridView的数据进行排序

How to sort the data in grid view? 如何在网格视图中对数据进行排序?

How to sort data into GridView 如何将数据排序到GridView中

Sorting Data in a GridView 在GridView中对数据进行排序

How to sort GridView? 如何排序GridView?

I've done something like this in the past to sort a DataTable: 我过去做过类似的事情来对DataTable进行排序:

DataTable dt = new DataTable(); // your data table
dt.DefaultView.Sort = "your_field" + "sort_direction";
DataView dv = new DataView(dt);
dv.Sort = ("your_field" + "sort_direction");
yourGridView.DataSource = dv;

When sorting, make sure to cast your table to a DataView. 排序时,请确保将表转换为DataView。 You'll save yourself a lot of time over manually implementing sorting methods. 您可以节省大量时间来手动实现排序方法。

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

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