Monday 11 May 2009

This row already belongs to another table ASP.NET

Just a quick look at a problem I came across when trying to copy rows from one datatable to another.

I originally tried this:

for i as integer = 0 to DT.rows.count - 1
newDT.rows.add(DT.rows(i))
next

ASP.NET threw a hissy fit at me and gave me the "This row already belongs to another table" error. I haven't looked to far into this but I assume the datarow objects are bound to a row schema inherited from the datatable schema. A bit of googling led me to the following solution:


for i as integer = 0 to DT.rows.count - 1
newDT = DT.Clone
newDT.ImportRow(DT.Rows(i))
next

So there we go, the clone function copies the schema from the first table to the second which allows for the importing of our rows.

1 comment:

Unknown said...

Suposing the two datatables have the same structure, you can just use:

dtSecont.Rows.Add(dtFirst.Rows[0].ItemArray);

I hope it helps!