I need to resort, in memory, a DataTable based on a column and direction that are coming from a GridView. The function needs to look like this:
public static DataTable resort(DataTable dt, string colName, string direction) { DataTable dtOut = null; .... }
I need help filling in this function. I think I can use a Select statement but I am not sure how. I can't click on Comments because of this browser but you can show me an in-place or new DataTable solution, either one. For the people showing me pointers, please, I need a coded function similar to the one prototyped.
How about:
// ds.Tables[0].DefaultView.Sort="au_fname DESC"; public static void Resort(ref DataTable dt, string colName, string direction) { string sortExpression = string.Format("{0} {1}", colName, direction); dt.DefaultView.Sort = sortExpression; }
The existing answers are using legacy DataTables syntax. Versions 1.10+ should use the following syntax: $('table'). dataTable({ "pageLength": -1, //display all records "order": [[ 0, "desc" ]] // Sort by first column descending });
Using the order initialisation parameter, you can set the table to display the data in exactly the order that you want. The order parameter is an array of arrays where the first value of the inner array is the column to order on, and the second is 'asc' (ascending ordering) or 'desc' (descending ordering) as required.
I assume "direction" is "ASC" or "DESC" and dt contains a column named "colName"
public static DataTable resort(DataTable dt, string colName, string direction) { DataTable dtOut = null; dt.DefaultView.Sort = colName + " " + direction; dtOut = dt.DefaultView.ToTable(); return dtOut; }
OR without creating dtOut
public static DataTable resort(DataTable dt, string colName, string direction) { dt.DefaultView.Sort = colName + " " + direction; dt = dt.DefaultView.ToTable(); return dt; }
If you've only got one DataView, you can sort using that instead:
table.DefaultView.Sort = "columnName asc";
Haven't tried it, but I guess you can do this with any number of DataViews, as long as you reference the right one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With