Sunday, July 6, 2008

Difference between Copying and Cloning the DataTable

Copying and Cloning the DataTable: You often need to create a full copy of a DataTable in your application, possibly to pass it to another application, or to use as a scratch pad for operations that may be thrown out later.

For example, you may want to assign a DataTable object to a GridView control to allow a user to edit the data, but you also may want to provide a cancel button that aborts all changes on the Web page.

A simple way to implement this functionality is to create a copy of your DataTable object and use the copy for editing. If the user clicks the cancel button, the DataTable copy is thrown out.

If the user decides to keep the changes, you can replace the original DataTable object with the edited copy.

To create a copy of a DataTable object, use the Copy method on the DataTable, which copies the DataTable object schema and data.

The following code snippet shows how to invoke the Copy method:
'VB
Dim copy as DataTable = employee.Copy( )
 
//C#
DataTable copy = employee.Copy( );

You often require a copy of the DataTable schema without the data. You can accomplish this by invoking the Clone method on the DataTable. Use this method when an empty copy of the DataTable is required and to which DataRow objects will be added at a later time.

The following code shows the Clone method:

'VB
Dim clone as DataTable = employee.Clone( )
//C#
DataTable clone = employee.Clone( );