Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you Sort a DataTable given column and direction?

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;    } 
like image 509
Sam Gentile Avatar asked Feb 15 '11 15:02

Sam Gentile


People also ask

How do I sort a specific column in a DataTable?

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

How do you show data in descending order in DataTable?

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.


2 Answers

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; } 
like image 186
Berkay Turancı Avatar answered Oct 07 '22 13:10

Berkay Turancı


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.

like image 21
Alex Avatar answered Oct 07 '22 13:10

Alex