A beginner in C#, most of the time get error “This row already belongs to another table” while adding Row from one DataTable to another DataTable.
The reason of this error is that, we cannot add row of one table into another directly, we have to use the API of C# as shown below:
// This example generates the error // ds is a dataset that has previously been populated DataTable dt1 = ds.Tables[0]; DataTable dt2 = new DataTable(); foreach(DataRow row in dt1.Rows){ if(row["Column1"] == 10){ // This line generates the error... dt2.Rows.Add(row); } }
The correct way to copy the row is :
// This example achieves the copy // ds is a dataset that has previously been populated DataTable dt1 = ds.Tables[0]; DataTable dt2 = new DataTable(); dt2 = dt1.Clone(); foreach(DataRow row in dt1.Rows){ if(row["Column1"] == 10){ // Import the Row into dt2 from dt1 dt2.ImportRow(row); } }
Leave a Reply