copy datarow in other datatable
Hi,
I am trying to create a procedure that can copy datarows in other datatables. I have a dataset with one datatable and this datatable contains 10 datarows. I want to create 10 seperate datasets each containg one datatable. This datatable contains only one datarow. This datarow should be a copy of the datarow in the first datatable (the one with the 10 datarows).
Thanks for reading my problem.
This is my test code, but it does not work.
Code:
'connection class
Dim c As New clsSQLConnection("localhost", "northwind", "sa", "sa")
'dataset class
Dim d As New clsSQLDataset(c)
'fill the dataset
d.fillDataset(Chr(34) & "sales by year" & Chr(34) & " '1990', '2004'")
'a new collection
Dim coll As New Collection
Dim tmpDS As DataSet
Dim tmpTable As DataTable
Dim tmpRow As DataRow
For Each dr As DataRow In d.dtSet.Tables(0).Rows
tmpDS = New DataSet
tmpTable = New DataTable
tmpTable.Rows.Add(dr)
'An unhandled exception of type 'System.ArgumentException'
'occurred in system.data.dll
'Additional information:
'This row already belongs to another table.
tmpDS.Tables.Add(tmpTable)
coll.Add(tmpDS)
Next
MsgBox(coll.Count)
Re: copy datarow in other datatable
i got exactly the same problem.
any help ?
Re: copy datarow in other datatable
You don't copy a DataRow TO another DataTable, but rather you copy it FROM another DataTable. Check out the DataTable.ImportRow method.
For the original problem, you would call Clone on the original DataTable to replicate the structure and then ImportRow on the new DataTable:
VB Code:
Dim newDataSet As New DataSet
Dim newDataTable As DataTable
For i As Integer = 0 To myTable.Rows.Count - 1 Step 1
newDataTable = myTable.Clone()
newDataTable.ImportRow(myTable.Rows(i))
newDataSet.Tables.Add(newDataTable)
Next i
Re: copy datarow in other datatable