"This row already belongs to another table" Error
What an annoying error!! I couldn't believe that I couldn't just add a Row from one DataTable to another, while looping around a DataTable's Rows.
It turned out to be slightly more complicated than the code I had written, I've simplified the code below from what I was actually doing in the loop, but you'll get the idea.
// This example generates the error
// ds is a dataset that has previously been populated
DataTable dt1 = ds.Tables[0];
DataTable dt2 = new DataTable();
foreach(DataRow row in dt1.Rows){
if(row["Column1"] == 10){
// This line generates the error...
dt2.Rows.Add(row);
}
}
The correct way to achieve this is to clone dt2 on dt1, this creates the appropriate columns, then when you want to copy the row from dt1 into dt2 you use the ImportRow Method.
// This example achieves the copy
// ds is a dataset that has previously been populated
DataTable dt1 = ds.Tables[0];
DataTable dt2 = new DataTable();
dt2 = dt1.Clone();
foreach(DataRow row in dt1.Rows){
if(row["Column1"] == 10){
// Import the Row into dt2 from dt1
dt2.ImportRow(row);
}
}
Once I'd found the solution to this problem it made perfect sense.
If you've just got this error, I hope this helped you out.
Time for a 