ArgumentException – This row already belongs to another table
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); }
Comments
Post a Comment