Wednesday, November 9, 2011

How to sort and filter DataTable rows in C#

To explain with an an example I am creating a DataTable


DataTable dt = new DataTable();


You can add columns in one of these two ways
            
DataColumn id=new DataColumn("ID",Type.GetType("System.Int32"));
DataColumn name=new DataColumn("Name",Type.GetType("System.String"));


or 


dt.Columns.Add(id,typeof(int));
dt.Columns.Add(name,typeof(string));


Then add rows of data


dt.Rows.Add(10,"Bharath");
dt.Rows.Add(5,"Kumar");




Here we use DataTable Select method for filtering and sorting the data. I am not providing any parameter for first parameter (filter) and I am sorting the Data by ID (by default in Ascending order). If you want in Descending order mention "ID DESC"


if you want to filter data for ids > 5 then you can mention the first parameter as "ID > 5"


DataRow[] dr=dt.Select("","ID")


You will get the sorted Row Array in dr variable. Check ItemArray of dr variable for values.


Please provide your comments

No comments:

Post a Comment