Reputation: 4305
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.
Upvotes: 1
Views: 18458
Reputation: 39255
Two solutions spring to mind:
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.
Upvotes: 11
Reputation: 39697
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);
}
}
Upvotes: 3