We can filter data in Datatable using Datatable.Select method. We can also sort the filtered data.
We can also apply AND , OR conditions while filtering and sorting.
Sample Datatable
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
static DataTable FillDatatoGrid() { DataTable dt = new DataTable("Emp"); //Adding columns to table Emp DataColumn colEmpid = new DataColumn("Empid", typeof(System.Int32)); DataColumn colName = new DataColumn("Name", typeof(System.String)); DataColumn colDept = new DataColumn("Department", typeof(System.String)); //Adding columns to datatable dt.Columns.AddRange(new DataColumn[] { colEmpid, colName, colDept }); //Adding data dt.Rows.Add(1000, "John Smith Brown", "Finance"); dt.Rows.Add(1001, "Carry Brown", "Engineering"); dt.Rows.Add(1002, "Candle Pencil", "Marketing"); dt.Rows.Add(1003, "Graham Bell", "Engineering"); dt.Rows.Add(1004, "Peter Kevin", "Finance & Engineering"); return dt; } |
Example program to Filtering Data using Datatable.Select Method , AND, OR Conditions and Sorting.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
class Program { static DataTable FillDatatoGrid() { DataTable dt = new DataTable("Emp"); //Adding columns to table Emp DataColumn colEmpid = new DataColumn("Empid", typeof(System.Int32)); DataColumn colName = new DataColumn("Name", typeof(System.String)); DataColumn colDept = new DataColumn("Department", typeof(System.String)); //Adding columns to datatable dt.Columns.AddRange(new DataColumn[] { colEmpid, colName, colDept }); //Adding data dt.Rows.Add(1000, "John Smith Brown", "Finance"); dt.Rows.Add(1001, "Carry Brown", "Engineering"); dt.Rows.Add(1002, "Candle Pencil", "Marketing"); dt.Rows.Add(1003, "Graham Bell", "Engineering"); dt.Rows.Add(1004, "Peter Kevin", "Finance & Engineering"); return dt; } static void Main(string[] args) { //Fill data into datatable. FillDatatoGrid method is defined above DataTable dataTable = FillDatatoGrid(); //using Datatable.Select Method DataRow[] rowsFiltered = dataTable.Select("Empid=1000"); DataRow[] rowsFilteredSorting = dataTable.Select("Department='Engineering'", "Empid desc"); //Filtering datatable with OR Conditoin and Sorting DataRow[] rowsFilteredConditionOR = dataTable.Select("Empid=1000 OR Empid=1001", "Empid desc"); //Filtering datatable with AND Conditoin //Strings should be enclosed with single quotes DataRow[] rowsFilteredConditionAND = dataTable.Select("Empid=1001 AND Name='Carry Brown'", "Empid desc"); foreach (var item in rowsFilteredSorting) { Console.WriteLine("{0} \t{1} \t{2}", item[0],item[1],item[2]); } Console.ReadLine(); } } |
Please note, strings should be enclosed with single quotes while filtering data using Datatable.Select method.