Today one of my colleague got this problem while copying datarow from one table to another, he just want to update few values of a same schema dataTable. So he used following method.
for (var i = 0; i < 10; i++)
{
var row = dataTable.NewRow();
row[0] = i.ToString();
dataTable.Rows.Add(row);
}
for (int i = 0; i < 10; i++)
{
var dr = dataTable.Rows[i];
dr[0] = (i + 10).ToString();
//This line throws exception
dataTable1.Rows.Add(dr);
}
He was getting an exception like “This row already belongs to another table”. This exception is coming because of A DataRow can only belong to a single data table.
I got this exception many times (in good(?) old ASP.Net 1.1 days
) and able to fix, but today I couldn’t remember the solution. Later we fixed it, and here is the solutions.
- Using Item array property : Instead of using the row directly from other second table, use the ItemArray property.
var dr = dataTable.Rows[i].ItemArray; dr[0] = (i + 10).ToString(); dataTable.Rows.Add(dr);
- Using DataTable.Clone() and ImportRow() methods : Instead of using creating a new DataTable with same schema again, clone the DataTable and using ImportRow method.
DataTable dataTable1 = dataTable.Clone(); var dr = dataTable.Rows[i]; dr[0] = (i + 10).ToString(); dataTable1.ImportRow(dr);
Happy coding
and Thanks to Sarath
