Sort the data table using Select Method

Posted by VIJI Friday, July 3, 2009

Suppose we may want to Sort the data table based on a specific column before binding it it the GridView.

There are two ways to do it.

Method 1: Using DataView Sort property

DataTable dt;

DataView dv = new DataView(dt);
dv.Sort = " desc";


We can access the dataview instead of the datatable

Example:


DataTable dt;

DataView dv = new DataView(dt);
dv.Sort = "EmpID Asc";
dt= dv.toTable();

//Bind the data table to DataGridView
DataGridView1.DataSource = dt;
DataGridView1.Refresh();


This will sort the data table in Descending based on Employee ID.


Method 2 : Sorting using Select Method of Data Table


private static void SortDataTable(DataTable dt, string sortCol)
{
//Take a Clone of the DataTable

DataTable newDT = dt.Clone();
int rowCount = dt.Rows.Count; //Rows Count


//Using Select Method to sort the Rows
DataRow[] SortedRows = dt.Select(null, sortCol); // Sort with Column name
for (int i = 0 ; i < rowCount; i++)
{
object[] arr = new object[dt.Columns.Count];
for (int j = 0; j < dt.Columns.Count; j++)
{
arr[j]=SortedRows[i][j];
}

//Add the Sorted Row
DataRow data_row = newDT.NewRow();
data_row.ItemArray=arr;
newDT.Rows.Add(data_row);
}

//clear the incoming
dt.Rows.Clear();

for(int i = 0; i < newDT.Rows.Count; i++)
{
object[] arr = new object[dt.Columns.Count];
for (int j = 0; j < dt.Columns.Count; j++)
{
arr[j]=newDT.Rows[i][j];
}

DataRow data_row = dt.NewRow();
data_row.ItemArray = arr;
dt.Rows.Add(data_row);
}

dt.AcceptChanges();

//Bind the Sorted Table to DataGridView

DataGridView1.DataSource = dt;
DataGridView1.Refresh();

}

0 Responses to Sort the data table using Select Method

Post a Comment