This row already belongs to another table – Error

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

    }

}

Posted

in

,

by

Tags:


Related Posts

Comments

2 responses to “This row already belongs to another table – Error”

  1. Experts Comment Avatar
    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.

  2. Paresh Avatar
    Paresh

    Thanks a lot 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from Jitendra Zaa

Subscribe now to keep reading and get access to the full archive.

Continue Reading