Thursday, March 26, 2009

DataTable Manipulation

Here are some interesting ways to manipulate a DataTable.

First, to get the number of columns in a DataTable you can use the following code:

int colCount = myDataTable.Columns.Count;

To add a new column to a DataTable, you could use the following code:

myDataTable.Columns.Add(new DataColumn("myColumnName"));

To add a new row to the DataTable, use this:

myDataTable.Rows.Add(myDataTable.NewRow());



Read all the values in the DataTable: for (int r = 0; r < myDataTable.Rows.Count; r++ )
 {
     for (int c = 0; c < colCount; c++)
     {
     Console.WriteLine("row: {0} col: {1} value: {2}", r, c, myDataTable.Rows[r][c]);
     }
 } 


This is how you could find a row in the DataTable:
DataRow[] dRow = myDataTable.Select ("myNumericColumnName=123);

DataRow[] dRow = myDataTable.Select ("myStringTypeColumnName='abc'");


This method is much faster than going through each row and examining a column value.


Here is how you could add data from one DataTable to another one. The DataTables have  the same unique id field:

foreach (DataRow dr in myDataTable.Rows)
{
     //Find a corresponding row in the second DataTable
     DataRow[] drs = secondDataTable.Select("ID=" + dr["ID"].ToString());    
      if (drs.Length > 0)   
            dr["myField"] = drs[0]["myField"];
}