This row already belongs to another table – Error

Author posted by Jitendra on Posted on under category Categories c#, Microsoft and tagged as Tags with 2 Comments on This row already belongs to another table – Error

This row already belongs to another table – Error resolved

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);

    }

}

Related posts

  • Experts Comment

    Ya the best option is to go for ImportRow method of DataTable. This method copy the row from current table along with all the properties.

  • Paresh

    Thanks a lot