Copy columns from one data table to another, Column already belongs to another DataTable

Hi, I am using the Invoke method to add columns from DataTable DT to another DataTable MergedDT.

TargetType: (null)
TargetObject: MergedDT.Columns
MethodName: Add

Parameters:
In, DataColumn, DT.Columns(count)

In the first iteration where the MergedDT is supposed to be blank, I still get error Column already belongs to another DataTable.

I referred to this thread Column 'XXXX' already belongs to another DataTable but it appears I am already doing as the thread suggested.

How do I fix this error? Thanks

Hi @DEATHFISH,

Can you send this particular workflow?

Sorry, unable to do so because of client confidentiality requirement.

Perhaps you could provide the steps on how to copy entire columns from one table to another, looping column by column? Also I do not have Join Data Tables on my version of UiPath

@DEATHFISH - you want to copy the columns only not their data?

Columns with all the data contained within

You can see the sample workflow - It should solve your problem - you can improve as well by using loops for multiple columns instead of add one by one.

Let me know if you face any issue to understand the sample.CopyDataColumns.xaml (12.0 KB)

@DEATHFISH

You can use

DataTable1 = Datatable2.DefaultView.ToTable(flase, “Column1”, “Column2”).copytodatatable

or if u need only column with no data you can use

DataTable1 = Datatable2.Clone

3 Likes

Try creating a seperate datacolumn variable and assign the column to it and then use that variable to add column.

@Vijay_Tulsalkar

Does this preserve the contents of DataTable1 and just append the additional columns from DataTable2 to DataTable1?

@Avi7

Is it possible to just use the DataTable.Columns.Add and specify a DataColumn object as the input parameter? Instead of passing column name and data type

The function “DataTable.Columns.Add” accept 2 arguments, 1st - Column name which is string type and second Datatype which is System.type.

@Avi7

Initially the destination table is blank and has no data, so I get error when copying into it “There is no row at position 0”… how do I fix this?

If the 1st Datatable is empty and you want to add columns from another Datatable with data then you have to add rows to your 1st DT with\without values.

@Avi7

How do I do this?

Also I have to combine several tables together so I wouldn’t use the ToTable method for the first copy

If I add columns to a table with existing rows, will the existing rows contain the new columns?