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.
You create DataColumn objects within a table by using the DataColumn constructor, or by calling the Add method of the Columns property of the table, which is a DataColumnCollection. The Add method accepts optional ColumnName, DataType, and Expression arguments and creates a new DataColumn as a member of the collection.
In the data table structure, click the plus sign between the nodes where you want to add columns, and select Add columns.
To add a new row, declare a new variable as type DataRow. A new DataRow object is returned when you call the NewRow method. The DataTable then creates the DataRow object based on the structure of the table, as defined by the DataColumnCollection.
DataColumn(String, Type, String, MappingType) Initializes a new instance of the DataColumn class using the specified name, data type, expression, and value that determines whether the column is an attribute.
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];
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With