How can we copy the data of the datacolumn of the datatable to another datatable?
How开发者_C百科 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.
Two solutions spring to mind:
- after creating the column, loop through all rows to copy the data from the source to the target.
- 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.
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);
}
}
精彩评论