Column Filtering in a DataTable

We can filter specific columns of a DataTable and create another DataTable for those filtered columns using the following code snippet.

DataTable dtEmp = new DataTable();
dtEmp.Columns.Add("EmpNo", System.Type.GetType("System.Int32"));
dtEmp.Columns.Add("EmpName", System.Type.GetType("System.String"));
dtEmp.Columns.Add("Salary", System.Type.GetType("System.String"));
dtEmp.Columns.Add("Department", System.Type.GetType("System.String"));

dtEmp.Rows.Add(new object[] { 1001, "John", 45000, "Operations" });
dtEmp.Rows.Add(new object[] { 1002, "Harry", 65000, "Accounting" });
dtEmp.Rows.Add(new object[] { 1003, "Sujith", 75000, "Purchase" });
dtEmp.Rows.Add(new object[] { 1003, "Sujith", 51000, "Operations" });
dtEmp.Rows.Add(new object[] { 1003, "Sujith", 61000, "Purchase" });

DataTable dtFiltered = dtEmp.DefaultView.ToTable(false, new string[] { "EmpNo", "Salary" });

In the above code snippet, the DataTable object dtFiltered will have rows from dtEmp only for EmpNo and Salary columns.

The DataTable.DefaultView property returns a DataView object which can be used for sorting, filtering, searching, editing, and navigation operations . The DataView.ToTable() method creates and returns a new DataTable object based on the arguments passed to it. The first argument in this method is used to determine whether the output DataTable should have distinct values for all its columns. The next argument is an array of column names for which the output DataTable will have rows.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: