how to sort a DataTable by a specific column using C#

The majority of the time when displaying content to the end user you will want to order the data by certain criteria. More often than not you will want to sort by a specific column. If your data is in a DataTable how do you do that?

You need to convert your DataTable into a DataView, apply your sort and save the results back to your DataTable. Let's say we have a DataTable that holds details of all our customers and we want to order the information by their names. To keep things simple I will hard code in only 2 customer values here. You would order the information by doing the following:

using System.Data;

//create our datatable and setup with 2 columns
DataTable dt = new DataTable();
dt.Columns.Add("CustomerFirstname", typeof(string));
dt.Columns.Add("CustomerSurname", typeof(string));
DataRow dr;

//store some values into datatable
//just using 2 names as example
dr = dt.NewRow();
dr["CustomerFirstname"] = "John";
dr["CustomerSurname"] = "Murphy";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["CustomerFirstname"] = "John";
dr["CustomerSurname"] = "Doe";
dt.Rows.Add(dr);

//check to make sure our datatable has at
//least one value. For this example it's not
//really need but if we were taking the 
//values from a database then this would be
//very important!
if (dt.Rows.Count > 0)
{
   //convert DataTable to DataView
   DataView dv = dt.DefaultView;
   //apply the sort on CustomerSurname column
   dv.Sort = "CustomerSurname";
   //save our newly ordered results back into our datatable
   dt = dv.ToTable();
}

//display your datatable to the user by databinding
//to repeater/gridview

blog comments powered by Disqus

Get In Touch

Follow me online at TwitterFacebook or Flickr.

Latest Tweets