Wednesday, September 12, 2012

How to filter DataTable columns C# .Net

Add, Delete, Modify and Filter columns in a DataTable

Some times we need to filter some columns when we have a dataTable  with much more unused Data Columns then we think that How to filter only required columns after removal of useless columns. Here I am giving you a solution this might be useful for you.

            string unUsedColumnNames = "col1,col2,col3";
            DataTable dt1 = (DataTable)Session["data"];     //  I have a DataTable stored in session
            DataTable dt2 = new DataTable();
            dt2 = dt1.Copy();
            foreach (DataColumn column in dt1.Columns)
            {
                if (unUsedColumnNames.Contains(column.ColumnName))
                {
                    dt2.Columns.Remove(column.ColumnName);
                }
            } 

Now we get dt2 as filtered DataTable from original DataTable dt1.

0 comments:

 
Powered by Code Imagine