Search code examples
c#datatablecopyclone

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?


Solution

  • 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
            .Tables[tableName]
            .GetChanges(DataRowState.Modified);
    
        //... 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]