Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding DataColumn to DataTable

Tags:

c#

datatable

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.

like image 282
escobar_season Avatar asked Jul 19 '12 15:07

escobar_season


People also ask

How to Add DataColumn in DataTable c#?

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.

How to Add a new column in DataTable?

In the data table structure, click the plus sign between the nodes where you want to add columns, and select Add columns.

How to Add DataTable rows in c#?

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.

What is DataColumn in C#?

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.


1 Answers

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];
    }
}
like image 77
Tim Schmelter Avatar answered Nov 03 '22 10:11

Tim Schmelter