Monday, July 26, 2010

Error: This row already belongs to another table

I came across a situation where i had to loop through one of the DataTable and to import the same data into another datable where the data order is different. I was trying to do it but the data is not getting copied to the new DataTable. What I have found out is that you can’t just add rows from one DataTable to another. Initially the table structure must be Cloned and then the rows has to be imported. Cloning the DataTable clones the structure including all DataTable schemas and constraints.

DataTable newTable = new DataTable("Sorted");

newTable = transactionHistoryTable.Clone();
for (int j = transactionHistoryTable.Rows.Count - 1; j >= 0; j—)
{
  newTable.ImportRow(transactionHistoryTable.Rows[j]);
}

_dsResponse.Tables.Add(newTable);

as a summary what i am doing is, initially the data what i have is some data in some order which was populated from AS400 API. I need the same data other way around, bottom to top (For ex: transactionHistoryTable has some data and i need to traverse it back).

0 comments: