views:

48

answers:

4

How to sort datatable obtained by GridView according to some column. 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);
}
A: 

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.

This is a pretty good summary with links to examples:

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

David
A: 

Add the attributes OnSorting="gridView_Sorting" AllowSorting="true" in Gridview

and SortExpression="ColumnName" in the column

and implement OnSorting Event.

check the links

Sorting the GridView's Data

How to sort the data in grid view?

How to sort data into GridView

Sorting Data in a GridView

How to sort GridView?

Azhar
+1  A: 

I've done something like this in the past to sort a 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;
Brissles
A: 

When sorting, make sure to cast your table to a DataView. You'll save yourself a lot of time over manually implementing sorting methods.

Jason M