Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Combining/Merging DataTables 1

Status
Not open for further replies.

1Data

MIS
Sep 30, 2005
66
US
I need to combine 2 DataTables into 1..How can I do this. FYI I know about the merge for Datasets this won't work for what I need to do.

I thank you in advance..
 
You need to loop through each row of each data table and use the copy method.

Somthing like:
Code:
For i = 0 To YourDataTable.Rows.Count - 1
   YourNewDataTable.Rows.Add(YourDataTable.Copy.Rows(i))
Next

...

And another loop here for the second datatable.

Jim
 
integer. you are looping through the rows from 0 to rowcount -1. The row collection is 0 based.

Dim i as Integer
 
For i = 0 To All.Rows.Count - 1
All2.Rows.Add(All.Copy.Rows(i))
Next

I get this exception?

This row already belongs to another table
 
Well it seems the row copy copyies the structure as well as the data and I think that is causing the problem. You can create some nasty nested loops to loop through each row and each column in each row and assing to the new data table.
What I did was to use a short cut. I used intermediary datasets and used them to merge the data.
Code:
''Add datatables to the datasets, one table per dataset.
   Dim ds1 As New DataSet
   ds1.Tables.Add(dt1)
   Dim ds2 As New DataSet
   ds2.Tables.Add(dt3)

''This is the final dataset with the merged rows.
   Dim dsNew As New DataSet
   dsNew.Merge(ds1)
   dsNew.Merge(ds2)

''Now create a final datatable from the final dataset.
   Dim dtNew As New DataTable
   dtNew = dsNew.Tables(0)

Jim
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top