13

I have two datatables one has few rows other is empty. I am running a loop over first one to copy some of the rows to another table. I am getting error 'The row already belongs to another table'.

Is there any way to copy DataRows one by one to other DataTable.

thanks in advance

MaxRecursion
  • 4,773
  • 12
  • 42
  • 76

2 Answers2

29

Use

newtable.ImportRow(oldtable.Rows[i]) 

where i is the desired row number.

as explained in http://support.microsoft.com/kb/308909/en-us

Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
3

copy the ItemArray, of course just works when the columns are the same

var dtCopyTo = new DataTable();
foreach(var rowCopyFrom in dtCopyFrom.Rows)
{
    var updatedDataRow = dtCopyTo.NewRow();
    updatedDataRow.ItemArray = rowCopyFrom.ItemArray;
    dtCopyTo.AddRow(updatedDataRow);
}

ps: code is typed without ide so check syntax pls

Community
  • 1
  • 1
blindmeis
  • 22,175
  • 7
  • 55
  • 74