Copy a DataTable in ADO.NET 2.0 - Free ADO.NET Tutorials

Copy a DataTable in ADO.NET 2.0

by  David Hayden ( Florida .NET Developer )

 

I have been spending some time each day answering questions on the MSDN Forums.  It is a great way to help people as well as a great learning experience because I often need to double-check if something actually works as expected.  I particularly like the questions about ADO.NET 2.0 concerning DataTables, DataAdapters, etc. because I don't normally get to play with these on a daily basis as I tend to use classes and collections.

I thought I would start sharing some of the questions and answers on my blog thinking they would perhaps be useful to others.

A question came up on the best way to copy a DataTable and my gut was that the DataTable probably had a Copy method for this, but I wasn't sure.  Turns out it does, and it indeed makes a copy of a DataTable based on my test shown below:

 

string connectionString =
"...Northwind ConnectionString..."; DataTable categories = new DataTable("Categories"); using (SqlConnection connection =
new SqlConnection(connectionString)) { SqlCommand command = connection.CreateCommand(); command.CommandText = "SELECT [CategoryID],
[CategoryName] FROM [Categories]
"; connection.Open(); categories.Load(command.ExecuteReader
(CommandBehavior.CloseConnection)); } DataTable copyOfCategories
= categories.Copy(); categories = null; // copyOfCategories is not null at this point,
so this will work...

 

When I set the original DataTable, called Categories, to null after the copy, the new DataTable, called copyOfCategories, still contains the original schema and data.

That's a handy method :)

 

Source:  David Hayden ( Florida .NET Developer )

 

Free ADO.NET Tutorials

 

posted on Tuesday, February 07, 2006 6:53 PM

Main

News

Green Tea

.NET Development

Enterprise Library

Patterns & Practices