How to custom sort a datatable

You can do this by creating a DataView on your table. Suppose you have a table named myTable that is to be sorted first by Column1 in ascending order and second by Column2 in descending order. This can be done as follows:

  1. Assign myView = New DataView(myTable) as a DataView variable;
  2. Assign myView.Sort = "Column1, Column2 DESC".

myView now has the desired result, which you can access by a For Each loop, setting its TypeArgument to DataRowView. They are similar to normal DataRow objects, so you can get items in a row by their column index or name as usual. If you need to have the sorted table as a DataTable object, you can get it with myView.ToTable.

5 Likes