Reputation: 530
I tried to sort a data table with following two ways
table.DefaultView.Sort = "Town ASC, Cutomer ASC"
table.Select("", "Town ASC, Cutomer ASC")
But none of them wasn't worked. It always displays data in original order. Do you have any idea to solve the problem.
Upvotes: 44
Views: 165550
Reputation: 4132
This worked for me:
dt.DefaultView.Sort = "Town ASC, Cutomer ASC";
dt = dt.DefaultView.ToTable();
Upvotes: 1
Reputation: 765
This was the shortest way I could find to sort a DataTable without having to create any new variables.
DataTable.DefaultView.Sort = "ColumnName ASC"
DataTable = DataTable.DefaultView.ToTable
Where:
ASC - Ascending
DESC - Descending
ColumnName - The column you want to sort by
DataTable - The table you want to sort
Upvotes: 65
Reputation: 16144
Try this:
Dim dataView As New DataView(table)
dataView.Sort = " AutoID DESC, Name DESC"
Dim dataTable AS DataTable = dataView.ToTable()
Upvotes: 42
Reputation: 216291
After setting the sort expression on the DefaultView (table.DefaultView.Sort = "Town ASC, Cutomer ASC"
) you should loop over the table using the DefaultView not the DataTable instance itself
foreach(DataRowView r in table.DefaultView)
{
//... here you get the rows in sorted order
Console.WriteLine(r["Town"].ToString());
}
Using the Select method of the DataTable instead, produces an array of DataRow. This array is sorted as from your request, not the DataTable
DataRow[] rowList = table.Select("", "Town ASC, Cutomer ASC");
foreach(DataRow r in rowList)
{
Console.WriteLine(r["Town"].ToString());
}
Upvotes: 36