Gino Abraham's Blog

October 2009 Entries

DataTable manipulation in C#

Often we would have came across a requirement where we have to filter a data table rows and copy the filtered data into a different datatable and bind the same to grid or some other data bound control.
 
This can be achieved in several ways. One such way is given below.
The initial section in the code is to create a sample data table with some sample records.
 
Then the data table is queried with a filter condition to get collection of rows. (dtTaskList.Select("TaskEffort>=5").Clone())
 
Once done with your filtered row collection add them to a new data table which has similar skelta.
 
The sample out here is just show you how to strip a data row from a data table and add a copy to a different table.
  
 
using System;
using System.Data;
 
namespace ConsoleApplication1
{
    classProgram
    {
        staticvoid Main(string[] args)
        {
 
            // Creating Sample Data Table
           
            DataTable dtTaskList = newDataTable();
 
            DataColumn dc = newDataColumn("TaskName");
 
            dtTaskList.Columns.Add(dc);
 
            dc = newDataColumn("TaskEffort", Type.GetType("System.Int32"));
 
            dtTaskList.Columns.Add(dc);
                 
            DataRow drTask = dtTaskList.NewRow();
 
            drTask[0] = "SampleTask1";
            drTask[1] = "5";
 
            dtTaskList.Rows.Add(drTask);
 
            drTask = dtTaskList.NewRow();
 
            drTask[0] = "SampleTask2";
            drTask[1] = "4";
 
            dtTaskList.Rows.Add(drTask);
 
            // Sample Data Table creation ends here.
 
 
            // Querying a Data table with some filter condtion
            DataRow[] drRowArr = (DataRow[])dtTaskList.Select("TaskEffort>=5").Clone();
 
            // copy the skelta of the source table
            DataTable dtDestinationTable = dtTaskList.Clone();
 
            //loop thru the data row collection and insert into destination table
            foreach (DataRow dr in drRowArr)
            {
                dtDestinationTable.LoadDataRow(dr.ItemArray, false);
            }
 
 
        }
 
      
    }
}
 
if you are looking at a just filtering a data table and showing the filtered result set in a Data bound control the following snippet will help you.
 
 DataView dv = newDataView(dtTaskList, filterString, string.Empty, DataViewRowState.CurrentRows);
 
FilterString is similar to the string that is passed in Select method of a datatable