Wednesday, September 21, 2011

How to sort Rows/Data in a DataTable

We can sort binding source, data view and data table default view to sort data in a data table. There are following three methods which can be applied:

Method 1:
bindingSource.DataSource = table
dataGridView.DataSource = bindingSource
bindingSource.Sort = "Column_Name"

Method 2:
Alternatively, you can just use a DataView:

Dim view as DataView = new DataView(table)
view.Sort = "Column_Name"
dataGridView.DataSource = view

Method 3:
or change the DataTable's DefaultView:

table.DefaultView.Sort = "Column_Name"

Column_Name is the name of one or more columns on which a sort is required. So a Column_Name can have following values like: "COUNTRY" or "COUNTRY, POPULATION" or "COUNTRY, POPULATION DESC".