Adding DataColumn to DataTable
c#, datatable
Solution
You need to copy the properties like `ColumnName` and create new `DataColumns`:
foreach (DataColumn col in dt.Columns)
{
dt1.Columns.Add(col.ColumnName, col.DataType);
}
There's a reason for the `ArgumentException` when you add a `DataColumn` which already belongs to another DataTable. It would be very dangerous to allow that since a `DataTable` holds a reference to their columns and every column holds a reference to it's DataTable. If you would add a column to another table your code would blow sooner or later.
If you also want to copy the `DataRows` into the new table:
foreach (DataRow row in t1.Rows)
{
var r = t2.Rows.Add();
foreach (DataColumn col in t2.Columns)
{
r[col.ColumnName] = row[col.ColumnName];
}
}
Problem
I want to move the data from a `dataColumn` to a specific column in my `dataTable`. I am not sure how to specify what column within my `Datatable` I want to add the `datacolumn`. ``` foreach (DataColumn col in dt.Columns) { dt1.Columns.Add(col); } ``` I receive an exception `Column 'X' already belongs to another DataTable.`