VB.Net DataTable.Copy Method (System.Data)

In VB.NET, you can create a copy of a DataTable by using the DataTable.Copy method. This method allows you to duplicate the structure, including columns, constraints, and data, from an existing DataTable into a new one.

DataTable Copy

You can use the Copy method to create a shallow copy of a DataTable. This copy will have the same structure, including columns and constraints, but it will not include any data. Here's an example:

' Create a sample DataTable Dim originalTable As New DataTable() originalTable.Columns.Add("ID", GetType(Integer)) originalTable.Columns.Add("Name", GetType(String)) ' Add some data to the original table originalTable.Rows.Add(1, "Barack") originalTable.Rows.Add(2, "Bobby") ' Create a copy of the original table Dim copiedTable As DataTable = originalTable.Copy() ' Check the structure of the copied table For Each column As DataColumn In copiedTable.Columns Console.WriteLine($"Column Name: {column.ColumnName}, Data Type: {column.DataType}") Next ' Check if the copied table is empty Console.WriteLine($"Number of rows in copied table: {copiedTable.Rows.Count}")

In this example, copiedTable has the same structure as originalTable, but it does not contain any data.

Deep Copy with Data

If you want to create a deep copy that includes the data, you can use the Clone method to duplicate the structure and then manually copy the data from the original DataTable:

' Create a deep copy with data Dim deepCopyTable As DataTable = originalTable.Clone() For Each originalRow As DataRow In originalTable.Rows Dim newRow As DataRow = deepCopyTable.NewRow() newRow.ItemArray = originalRow.ItemArray deepCopyTable.Rows.Add(newRow) Next

This code creates a deep copy (deepCopyTable) that includes both the structure and data from the originalTable.

Constraints and Keys

The Copy method also preserves constraints defined on the original DataTable, such as primary keys, unique constraints, and foreign keys. If you want to copy these constraints, you can use Copy for this purpose.

Use Cases

Common use cases for copying DataTable include creating backup copies, applying changes or filters to the data in a separate table, or performing operations without affecting the original data.


You can use the DataTable.Copy method to create a shallow copy of an existing DataTable, preserving its structure (columns, constraints) but not its data. This is useful for tasks such as creating backup copies, filtering data in a separate table, or working with a copy of the original table without affecting the original data. If you need a deep copy that includes data, you can use the DataTable.Clone method in combination with manually copying the data.