How to put an existing DataTable into a DataSet?
Mia Lopez
That's just it. I have an existing DataTable, and I would like to make it a part of a existing DataSet. Any ideas on how to go about it? I tried a couple of things, but none of them work...
2 Answers
The Dataset contains a collection of Tables, and, as with every collection, you could use the method Add to add your table to the dataset.
However there is one thing to be aware of. If your table is already part of another dataset (probably because you used the DataAdapter.Fill(DataSet) method), then you should remove the table from the previous dataset tables collection before adding it to the new one.
Dim dsNew = New DataSet() ' The dataset where you want to add your table
Dim dt As DataTable = GetTable() ' Get the table from your storage
Dim dsOld = dt.DataSet ' Retrieve the DataSet where the table has been originally added
if dsOld IsNot Nothing Then dsOld.Tables.Remove(dt.TableName) ' Remove the table from its dataset tables collection
End If
dsNew.Tables.Add(dt) ' Add to the destination dataset. 0 You can use dataSet.Tables.Add(dataTable).
See DataTableCollection.Add for details.