1

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);
}

4 Answers 4

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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?

Comments

1

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;

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.