Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamic datatable sorting in ascending or descending

Tags:

c#

asp.net

I have created dynamic table

 DataTable date = new DataTable();
 date.Columns.Add("date1");

and made fill the column name "date1" with date as

date1(Column name)
05-07-2013
10-07-2013
09-07-2013 
02-07-2013 

and made fill my dynamic table

Now i want this dynamic table data to be sort as ascending or descending order

For eg:

date1(Column name)
02-07-2013
05-07-2013
09-07-2013 
10-07-2013 
like image 755
Mitesh Jain Avatar asked Jul 10 '13 13:07

Mitesh Jain


2 Answers

This cannot be done with the original data table. However you can create a new, sorted one:

DataView view = date.DefaultView;
view.Sort = "date1 ASC";
DataTable sortedDate = view.ToTable();
like image 114
Andrei Avatar answered Oct 23 '22 09:10

Andrei


You can use DataTable.Select(filterExpression, sortExpression) method.

Gets an array of all DataRow objects that match the filter criteria, in the specified sort order.

date.Select("", "YourColumn ASC");

or

date.Select("", "YourColumn DESC");

As an alternative, you can use DataView like;

DataView view = date.DefaultView;
view.Sort = "YourColumn ASC";
DataTable dt = view.ToTable();
like image 4
Soner Gönül Avatar answered Oct 23 '22 10:10

Soner Gönül