Monday, October 25, 2010

This row already belongs to another table?Column does not belong to table?


Sometimes when you're trying to copy some rows from existing data table to a new one you might get the error – "This row already belongs to another table". It's very annoying, but actually it makes sense. Let's look at following code snippet.

 
When you're trying to add existing DataRow from initialTable.DataRowCollection to newTable.DataRowCollection the exception is thrown.

Actually,DataRowCollection.Add method calls internal DataTable.InsertRow method, which checks DataRow.Table property and if it is set and not equaled to current DataTable the exception will be thrown. So, you can't share DataRows between your DataTables.

Another approach is to use DataTable.ImportRow method to add existing DataRow.
 
DataTable.ImportRow method copies existing DataRow into a DataTable, preserving any property settings, as well as original and current values. It actually calls DataTable.NewRow method on destination DataTable with current table schema and then copies all values to this new DataRow and inserts into DataTable. And everything seems to be ok, unless you try to access data from newTable.
If you try this code you will get an exception "Column does not belong to table". And it's logical because we have different schemas (structures) for our DataTables. Actually, newTable doesn't know anything about ID column, so in order to use newTable.DataRowCollection and access columns from each row we should first clone initialTable structure to newTable. To copy initialTable structure (shcema) we could use DataTable.Clone method and then we could easily use newTable as a copy or some filtered subset of initialTable.