Sep 3, 2012

ArgumentException – This row already belongs to another table

1 comment
While creating new DataTable from another (which is loaded with XML) one in one of requirement, I came across an exception saying that, “ArgumentException was unhandled - This row already belongs to another table.”
Following code (here providing code that simulates my actual program) produces the above mentioned error,

DataTable dt1 = new DataTable();
dt1.Columns.Add("test");

// Add rows
for (int i = 0; i < 5; i++)
{
    DataRow row = dt1.NewRow();
    row["test"] = i.ToString();
    dt1.Rows.Add(row);
}

// Copy rows from first dataTable(dt1) after modification to dataTable(dt2)
DataTable dt2 = new DataTable();
for (int i = 0; i < 5; i++)
{
    DataRow rowToModify = dt1.Rows[i];
    rowToModify["test"] = string.Format("{0} Modified", i);
    dt2.Rows.Add(rowToModify);
}

foreach(DataRow row in dt2.Rows)
    rtxtOutput.Text += row["test"].ToString();

This indicates that, we cannot add or copy row from one DataTable to another dataTable directly. Then, how to solve this error? See the below example,

// Copy rows from first dataTable(dt1) after modification to dataTable(dt2)
DataTable dt2 = dt1.Clone();
for (int i = 0; i < 5; i++)
{
    DataRow rowToModify = dt1.Rows[i];
    rowToModify["test"] = string.Format("{0} Modified", i);
    dt2.ImportRow(rowToModify);
}
What we did here is,
- Clone the schema of source table (dt1) instead of creating new one.
- Modify row data of source table (dt1).
- Add modified row to destination table (dt2) using ImportRow method of DataTable.

1 comment :