16

I have a problem with my asp.net website, I am trying to copy a data row from one data table to another data table, but every time I am trying to do this i am getting an error:

This row already belongs to another table.
Jaymin
  • 2,879
  • 3
  • 19
  • 35

2 Answers2

17

As the error states, a DataRow instance is tied to its owning DataTable and cannot be added to another table.

Instead, use the ImportRow() method to make an actual copy of the row.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • 1
    Ok, Microsoft... you realize that is the case, why not, instead of throwing a smug exception, you run ImportRow in that case for us? *sigh* – Sean Kendle Jan 09 '14 at 19:13
  • 1
    @SeanKendle: No; having add sometimes make a copy of the row with no indication would be a very bad idea. – SLaks Jan 09 '14 at 19:56
  • Is there a case where saying "add row" *wouldn't* mean make a copy? Or, where you can even use add row if it's already a member of another table? – Sean Kendle Jan 09 '14 at 21:52
  • @SeanKendle: `table.NewRow()`. Or, remove, then re-add. – SLaks Jan 09 '14 at 22:28
  • Ok, so, in my mind, my point stands. In the case where you're saying "add this existing row (member of another table) to this other table", the language should be intelligent enough to know what you mean is "make a copy of the existing row, and add the copy to this table." Just my opinion. Sometimes VB.net isn't very intuitive. – Sean Kendle Jan 10 '14 at 14:32
  • @SeanKendle: No; that's exactly the opposite. The `Add()` method everywhere adds an _existing_ instance to a collection. Silently creating copies, especially only sometimes, is a horrible idea and is likely to lead to bugs. To put it differently, you don't want to write `a.Add(b)`, then discover that `b` is still not in `a`. – SLaks Jan 10 '14 at 14:38
4

For Example

You need to create a new Row with the values from dr first. A DataRow can only belong to a single DataTable.

You can also use Add which takes an array of values:

myTable.Rows.Add(dr.ItemArray)

Or probably even better:

myTable.ImportRow(dr);

Link

Community
  • 1
  • 1
Durgesh Pandey
  • 2,314
  • 4
  • 29
  • 43