views:

491

answers:

2

How can we copy one datacolumn with data from one datatable to another datatable ? I have datatable like

DataTable datatable1=new DataTable();

and there are four columns in that table but I want only one column.So I am doing like

DataTable datatable2=new DataTable(); 
addressAndPhones2.Columns.Add(addressAndPhones.Columns[0].ColumnName,addressAndPhones.Columns[0].DataType);

but this just adds the column but I want to copy the data for that column to the datatable2.That is I want to copy the datacolumn with data from one datatable to another datatable.

+3  A: 

Two solutions spring to mind:

  1. after creating the column, loop through all rows to copy the data from the source to the target.
  2. Do a datatable1.Copy() to copy all columns+data and delete the ones you don't need.

The second one is simpler to code but will copy unneeded data (which means extra time and memory).

For the first one, IF you have prepared the destiny-datatable AND the columnnames (and types) in source and destiny are the same:

private void CopyColumns(DataTable source, DataTable dest, params string[] columns)
{
  foreach (DataRow sourcerow in source.Rows)
  {
     DataRow destRow = dest.NewRow();
     foreach(string colname in columns)
     {
        destRow[colname] = sourcerow[colname];
     }
     dest.Rows.Add(destRow);
  }
}

You can use this like:

CopyColumns(source, destiny, "Column1", "column2");

naming any number of columns.

Hans Kesting
@Hans Kesting Sir,But I dont want all columns data but only fix no of datacolumns data then if I go through loop then which condition I should write for that.
Harikrishna
I added example code.
Hans Kesting
+2  A: 

You can loop over all rows with something like this:

private void CopyColumn(DataTable srcTable, DataTable dstTable, string srcColName, string dstColName)
{
    foreach (DataRow row in srcTable.Rows )
    {
        DataRow newRow = dstTable.NewRow();
        newRow[dstColName] = row[srcColName];
        dstTable.Rows.Add(newRow);
    }
}
Mikael Svenson
@Mikael Svenson,This works...But it adds the one column data only at a time if I want to copy more than one columns data a time what should I do ?
Harikrishna
@Mikael, Thank You...
Harikrishna
Extend the code to take more column names, should be pretty easy.
Mikael Svenson
@Mikeal,Thank you Sir +1 for the great answer.
Harikrishna