How to sort DataTable by two columns in c# How to sort DataTable by two columns in c# asp.net asp.net

How to sort DataTable by two columns in c#


You can use LINQ to DataSet/DataTable

var newDataTable = yourtable.AsEnumerable()                   .OrderBy(r=> r.Field<int>("ItemIndex"))                   .ThenBy(r=> r.Field<int>("ItemValue"))                     .CopyToDataTable();


Create a DataView and use the Sort Property:

DataView dv = new DataView(dt);dv.Sort = "ItemIndex, ItemValue";

e.g.

foreach (DataRowView row in dv) {   Console.WriteLine(" {0} \t {1}", row["ItemIndex"], row["ItemValue"]);}

For more information, check out MDSN for a more thorough example:

http://msdn.microsoft.com/en-us/library/system.data.dataview.sort.aspx


On the datatable object, just get the defaultview object and set the sort.

dataTable.DefaultView.Sort = "ItemIndex, ItemValue";