Wednesday, December 3, 2008

[.NET] How to sort DataTable

There's no way to automatically sort a DataTable after it's populated.

A way around this is to sort the DefaultView of the DataTable (or any other DataView associated with the DataTable).

You can achieve this using the Sort property of the DataView. This is a string which specifies the column (or columns) to sort on, and the order (ASC or DESC).

myDataTable.DefaultView.Sort = "myColumnOfChoice DESC";

The DefaultView can now be used as datasource for stuff or to do whatever you need it for.

10 comments:

Trav said...

Worked like a charm. Thanks!

silverunity said...

thanks man. worked awesomely.

Anonymous said...

Thanks.. This is helpful..

Anonymous said...

Thanks!!!

Aiyyappan P S said...

THANKS FRIEND.

Ali Faiyaz Shah said...

Working Perfectly

Rahul Bajaj said...

Thanks a ton

Harrison said...

MyStrongDataSet ds = new MyStrongDataSet();

ds.MyTable.DefaultView.Sort = "MySortColumnName";

Give that a try as well.

Harrison said...

Perfect! Thanks.

Daniel said...

Sweet, thanks for the tip