Tuesday, August 28, 2012

C# DataTable Order By Column


Sometimes when you work with DataSet or DataTable you need to order the data by specific column. The quickest way to sort DataTable by specific column is to convert it to DataView, apply the Sort method and then save back the results to your DataTable. Here is the code sample:
//   Create DataTable and fill out with data
DataTable table = new DataTable();  
table.Columns.Add("EmployeeFirstName", typeof(string));  
table.Columns.Add("EmployeeFamilyName", typeof(string));  
table.Columns.Add("Age", typeof(int));
DataRow row = table.NewRow();
  
row["EmployeeFirstName"] = "Bill";  
row["EmployeeFamilyName"] = "Gates";  
row["Age"] = 56;  
table.Rows.Add(row);  

row = table.NewRow();  
row["EmployeeFirstName"] = "Steve";  
row["EmployeeFamilyName"] = "Ballmer";  
row["Age"] = 57;  
table.Rows.Add(row); 

row = table.NewRow();  
row["EmployeeFirstName"] = "Paul";  
row["EmployeeFamilyName"] = "Allen";  
row["Age"] = 59;  
table.Rows.Add(row); 

//  In real life applications, it is critical 
//  to check if your DataTable is not empty!
if (table.Rows.Count > 0)  
{
    //  Convert DataTable to DataView
   DataView dv = table.DefaultView;
   //   Sort data
   dv.Sort = "Age";
   //   Convert back your sorted DataView to DataTable
   table = dv.ToTable();  
}

8 comments:

  1. Could you cut out the conversion to and from a DataView and just use

    table.DefaultView.Sort = "[Age] ASC";

    ReplyDelete
  2. thank u very much

    ReplyDelete
  3. Thank you very much

    ReplyDelete
  4. Its not working . datatable values are not showing in dataview

    ReplyDelete