Sorting rows in a data table

vidya sagar picture vidya sagar · Feb 2, 2012 · Viewed 501.1k times · Source

We have two columns in a DataTable, like so:

COL1   COL2
Abc    5
Def    8
Ghi    3

We're trying to sort this datatable based on COL2 in decreasing order.

COL1            COL2
ghi             8
abc             4
def             3
jkl             1

We tried this:

ft.DefaultView.Sort = "COL2 desc";
ft = ft.DefaultView.ToTable(true);

but, without using a DataView, we want to sort the DataTable itself, not the DataView.

Answer

Jay Riggs picture Jay Riggs · Feb 2, 2012

I'm afraid you can't easily do an in-place sort of a DataTable like it sounds like you want to do.

What you can do is create a new DataTable from a DataView that you create from your original DataTable. Apply whatever sorts and/or filters you want on the DataView and then create a new DataTable from the DataView using the DataView.ToTable method:

   DataView dv = ft.DefaultView;
   dv.Sort = "occr desc";
   DataTable sortedDT = dv.ToTable();