Wednesday, June 22, 2011

Output a DataTable in Random Order - VB.NET

To change the order of a DataTable to random, you need to change the DataTable to a DataView, add a column to the DataView, populate the fields of that column with random numbers, sort the DataView by that column, and then change the DataView back into a DataTable. The good news is this can be done in just a couple lines of code.


Dim myDataTable As DataTable
myDataTable = Whatever your data table is
myDataTable.Columns.Add(New DataColumn("RandNum", GetType(Integer)))
Dim i as Integer
Dim rndNum as New Random()
For i = 0 to myDataTable.Rows.Count - 1
myDataTable.Rows(i)("RandNum") = rndNum.Next(10000)
Next i
Dim myDataView as DataView = myDataTable.DefaultView
myDataView.Sort = "RandNum"
myDataTable = myDataView.ToTable()