Two methods to easily copy DataSet data and/or its structure to a new object (ADO.NET)

Occasionally, you may need to make a copy of a DataSet or its structure. Although you can't just assign the DataSet to a new DataSet object, you can use one of two ADO.NET methods to accomplish this task. If you want an exact copy of your DataSet data (schema, columns, and rows), you can use the DataSet Copy() method. The following code loads an XML file into a DataSet object and then creates an exact copy of it:

Dim ds As New DataSet
ds.ReadXml("C:\products.xml")
Dim ds1 As New DataSetds1 = ds.Copy

If your DataSet contains multiple tables and you only need a copy of one of them, the DataTable object also supports the Copy() method. The following code copies the first DataTable in the DataSet to a new table object:

Dim dt1 As New DataTable
dt1 = ds.Tables(0).Copy 

In addition to the Copy() method, both DataSet and DataTable objects support the Clone() method. Although this method sounds like it should perform the same task as Copy, it doesn't. The Clone method creates an exact copy of table schemas only. So, the next line adds the table and column names to the new Dataset, but no data:

Dim ds2 As New DataSet
ds2 = ds.Clone

0 comments: