Sam

Sam

  • NA
  • 166
  • 0

C# Update DataSet tables

Aug 11 2013 2:29 AM
I have a DataSet with 12 DataTables in 4 groups, each group having a common part of the TableName.
The DataTables are occasionally updated by the user (as DataGridViews), and need to be re-loaded to the dataset, replacing the existing tables.
With a single table, this is straightforward.

When I want to save back to the dataset a set of tables with common name part, I iterate (foreach) by table name and try to replace the relevant table(s).
As dataset tables can not be modified inside the foreach loop, I created a new temporary dataset by DataSet.Copy() and try to modify the new dataset (to replace later the original dataset).
I get the exception (for the new, tempDataSet!) "Table 'tablename' does not belong to this DataSet".

When checking the tables in both DataSets, they both have the same tables, but it seems like the tempDataSet tables are still bound to the original dataset.    
Here is a stripped simplified code:

DataSet tempDataSet = new DataSet();
                tempDataSet = fareDataSet.Copy();

                foreach (DataTable table in fareDataSet.Tables)
                {
                    if (table.TableName.Contains(faretype))
                    {
                       tempDataSet.Tables.Remove(table);   //<< Exception: "Table faretype-Summer does not belong to this DataSet"
                       tempDataSet.Tables.Add(table);
                    }
                }
                fareDataSet = tempDataSet.Copy();  //Copy back the temp to replace the original dataset.

I have also tried:
tempDataSet = fareDataSet;  //(omitting the .Copy())
In that case, on second iteration,  I get iteration error, as if I modified the dataset inside a foreach loop.
(which is not what I was doing!) I checked and found out that when updating the copied dataset, the original one is also updated, as if they were bound. 

Can anyone suggest the correct way to update the dataset ?
Thanks