C# - Sort the data table using Select Method

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();

}


Related Articles

Export Data to Excel in CSV format using .NET

Export Data to excel in CSV format. .NET code to export CSV data. Free .NET code to export data to excel. .NET way of exporting data to excel. Explanation of .NET code to export data to excel in CSV.

More articles: Export to Excel

Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: