dynamic datatable sorting in ascending or descending

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 

4 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(); 
0

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

Thought I would give in my two cents here. Instead of using a sorting algorithm which takes time and computational performance, why not instead reverse the way in which you are adding data to your data object.

This won't work for everyone's scenario - but for my own it worked out perfectly.

I had a database which listed items in an ascending order, but or ease of use I needed to reverse the way in which people could see the data (DESC) so that the newest input shows at the top, rather then the bottom of the list.

So, I just changed my for loop so instead of working from 0 -> upwards, it started from the length of the datatable (-1 to stop an overflow) and then stops when it is >= to 0;

private Dictionary<string, string> GetComboData(string table, int column, bool id, int idField = 0) { SqlClass sql = new SqlClass(database); Dictionary<string, string> comboBoxData = new Dictionary<string, string>(); if (sql.connectedToServer) { sql.SelectResults(SQLCommands.Commands.SelectAll(table)); for (int i = sql.table.Rows.Count-1; i >= 0; i--) { string tool = sql.table.Rows[i].ItemArray.Select(x => x.ToString()).ToArray()[column]; string ID = sql.table.Rows[i].ItemArray.Select(x => x.ToString()).ToArray()[idField]; comboBoxData.Add(ID, tool); } } return comboBoxData; } 

using OrderByDescending()

 @foreach (var rca in Model.OrderByDescending(x=>x.Id)) { <tr> <td>@rca.PBINo</td> <td>@rca.Title</td> <td>@rca.Introduction</td> <td>@rca.CustomerImpact</td> <td>@rca.RootCauseAnalysis</td> </tr> } 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like