Saturday, January 12, 2008

Easiest way to sort a datatable

If it is not typed:

Dim table1,table2 as DataTable
table1 = GetDataTable()
table1.DefaultView.Sort = "ColumnName"
table2 = table1.DefaultView.ToTable()

If the DataTable is typed:

Dim table1 as MyDataTable 'MyDataTable is a strongly typed DataTable
Dim table2 as New MyDataTable()
table1 = GetDataTable()
table1.DefaultView.Sort = "ColumnName"
table2.Load(table1.DefaultView.ToTable().CreateDataReader)

As simple as that.

This may not be very efficient but is very easy :)

1 comment:

Unknown said...

This works great! Even with typed data rows.

I would only add that you need to cast the rows back to the type you need.