How to Sort a column in a DataTable.

Posted by Tripati.patro under C# category on | Points: 40 | Views : 6105
There is no in-built method or property available on DataTable to sort a column. What we can do is use DataView which allows a column to be sorted.

var dtEmployee = new DataTable("Employee");
var dcId = new DataColumn("Id", typeof(System.Int16));
var dcName = new DataColumn("Name", typeof(System.String));

dtEmployee = LoadDataFromSource(); // Your code for populating data.

// Sort the data ase per name and store in another table.
var dvEmployee = dtEmployee.DefaultView;
dvEmployee.Sort = "Name Asc";
var dtNewEmployee = dvEmployee.ToTable(); // Sorted data is stored // Sorted data is stored

Comments or Responses

Posted by: T.saravanan on: 2/23/2011 Level:Silver | Status: [Member] [MVP] | Points: 10

In your code, what is cannot declare that one.
Posted by: Tripati.patro on: 2/24/2011 Level:Starter | Status: [Member] | Points: 10
Hi Saravan,

Thanks for the information. I modified the code.

Login to post response