How to tips and tricks for Microsoft Visual Studio .net

Monday, January 7, 2013

Copy or clone a DataTable and insert rows

From time to time you may have the need to make an exact duplicate of a DataTable. This is very easily done using the .clone() method.

The obvious place to start is to create a DataTable to use as the source...


    ' Create the Datatable
    Dim dtSource As New DataTable("Contacts")

    ' Create some columns for the table
    Dim colID As New DataColumn("id", Type.GetType("System.Int32"))
    Dim colFirstName As New DataColumn("FirstName", Type.GetType("System.String"))
    Dim colLastName As New DataColumn("LastName", Type.GetType("System.String"))

    ' Add the columns to the Datatable
    dtSource.Columns.Add(colID)
    dtSource.Columns.Add(colFirstName)
    dtSource.Columns.Add(colLastName)

    ' Create some rows to the DatatTable
    Dim row1 As DataRow = dtSource.NewRow()
    row1("id") = 1
    row1("FirstName") = "John"
    row1("LastName") = "Smith"

    Dim row2 As DataRow = dtSource.NewRow()
    row2("id") = 2
    row2("FirstName") = "James"
    row2("LastName") = "Bond"

    Dim row3 As DataRow = dtSource.NewRow()
    row3("id") = 3
    row3("FirstName") = "Jane"
    row3("LastName") = "Doe"

    ' Add the rows to the Data Table
    dtSource.Rows.Add(row1)
    dtSource.Rows.Add(row2)
    dtSource.Rows.Add(row3)

Now we have a DataTable with 3 columns and 3 rows called Contacts.

To make a copy of it we use the .Clone() Method...

    Dim dtTarget As DataTable = dtSource.Clone()

That's all there is to making an exact copy of the DataTable. One very important thing keep in mind is that the .Clone() method will only copy the structure and NOT the data or rows from the source DataTable.

If you want to import the rows from the source to the target DataTable, you must use the .ImportRow() method.

    For Each row As DataRow In dtSource.Rows
      dtTarget.ImportRow(row)
    Next

As always... Comments are welcome.


No comments:

Post a Comment