How to copy/clone a DataTable

I have a DataTable that will be modified by the user. I want to identify what's been change an keep record of that in the database.

The best way I see of doing this is by copying that DataTable before any changes are made and verify what's been changed when the user saves the form.

The problem is that wether I use myDataTable.Clone() or myDataTable.Copy(), the data are always the same. So I guess they just create references between the tables.

How would you handle this?


Try the DataSet.HasChanges method. This will tell you if there have been any changes to the dataset such as deleted or added rows, modified rows, etc.

You can also call DataSet.GetChanges to see what has changed. This method will return a copy of the changes.

For example, you could say:

private void VerifyChanges(DataSet dataSet)
    if(!dataSet.HasChanges(DataRowState.Modified)) return;
    var changedDataSet = dataSet.GetChanges(DataRowState.Modified);

    //... do the tracking or whatever else you want here.        

Or if you don't want to get all the DataSet changes, and just want the changes from a specific table:

private void VerifyChanges(DataSet dataSet, string tableName)
    if(!dataSet.HasChanges(DataRowState.Modified)) return;
    var changedTable = dataSet

    //... do the tracking or whatever else you want here.        

Lastly, to pull the original values out of the modified DataSet you could code:

row[columnIndex, DataRowVersion.Original]

IMO, the quick and dirty way would be to serialize then deserialize the DataTable. If you decide to use xml serialization, be sure to nest the DataTable within a DataSet first.

Consider use of DataTable.GetChanges Method (DataRowState). This method returns a new data table with the rows that were changed.


DataTable changeTable = table.GetChanges(DataRowState.Modified);

Having this table you can compare the rows one-by-one with another DataTable.

Need Your Help

Unit testing by mocking the data layer or using embedded database

java unit-testing derby easymock

For unit testing is it better to mock the data layer or use an embedded database like derby?

Disposing of Resources in .NET

c# memory garbage-collection idisposable

i have a stupid question, but i want to hear the community here.