ArgumentException – This row already belongs to another table

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.

ArgumentException – This row already belongs to another table

ArgumentException – This row already belongs to another 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.

  1. 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);
    
  2. 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

Leave a Reply

Your email address will not be published. Required fields are marked *

CAPTCHA Image

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>