0

Is it possible to sort an ASP.NET GridView using DataTable.Select("", sortExpression)?

I have a regular GridView with AllowSorting="true" and OnSorting="grdEmployees_Sorting".

protected void grdEmployees_Sorting(object sender, GridViewSortEventArgs e)
        {
            DataTable dt = getDataTable();

            var sortExprOrder = e.SortDirection == SortDirection.Ascending ? " ASC" : " DESC";

            var rows = dt.Select("", string.Format(e.SortExpression + "{0}", sortExprOrder));

            grdEmployees.DataSource = rows;
            grdEmployees.DataBind();
        }

Not sure why, but this does not work. The grid shows a bunch of rows with three columns, RowError, RowState, and HasErrors (contains rows with all empty checkboxes).

Am I doing something wrong?

1 Answer 1

1

You don't need select for sorting DataTable.Select is for filtering

This how you sort

protected void grdEmployees_Sorting(object sender, GridViewSortEventArgs e)
        {
            DataTable dt = getDataTable();

            var sortExprOrder = e.SortDirection == SortDirection.Ascending ? " ASC" : " DESC";

            DataView dv = new DataView(dt);
            dv.Sort = string.Format("{0} {1}",
                e.SortExpression, sortExprOrder);

            grdEmployees.DataSource = dv;
            grdEmployees.DataBind();
        }
Sign up to request clarification or add additional context in comments.

2 Comments

dt.Select("", sortExpression) returns DataRow[]. Why can't I assign an array of type DataRow to the DataSource of the GridView?
DataRow holds data in an ItemArray, so if you want to bind DataRow you need to bind collection of ItemArray like GridView1.DataSource = rows.Select(r => r.ItemArray[0]);

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.