Rohit Chaudhari
Rohit Chaudhari

Reputation: 757

Exception in copying DataRow to another DataTable

I have two data tables, dt1 & dt2. dt1 has data while dt2 is a new table. Now I want to copy some rows, satisfying particular condition, to dt2. I have tried following code, but I get this exception:

System.ArgumentException This row already belongs to another table.

foreach(DataRow dr in dt1.Rows)
{
   if(Convert.ToInt32(dr["col"]) == value)
   {
      dt2.Rows.Add(dr);
   }
}

How can I resolve this?

Upvotes: 1

Views: 2326

Answers (3)

andy
andy

Reputation: 6079

Every time when you add a row to the datatable it should be different(new) row........

Datarow newRow = null;
foreach(DataRow dr in dt1.Rows)
{
  if(Convert.ToInt32(dr["col"]) == value)
  {
   newRow = dt2.NewRow();
   newRow ["A"] = dr["A"];     
   dt2.Rows.Add(newRow );
  }
 }

Upvotes: 0

Nikhil Agrawal
Nikhil Agrawal

Reputation: 48600

You directly cannot "Add" a DataTable row from one to another since it belongs to souce Datatable. You can "Add" a newly created row to DataTable.

Hence you are getting this exception.

There are many ways to overcome this. Some are listed below

Method 1:

If you want to get a row from source Datatable and add in destination without any changes, then use ImportRow this way.

dt2.ImportRow(dr);

Method 2:

But if you want to take specific data. Then use this

foreach(DataRow dr in dt1.Rows)
{
   if(Convert.ToInt32(dr["col"]) == value)
   {
      Datarow ndr = dt2.NewRow();
      ndr["Foo"] = dr["Foo"];
      //..Similarly for other rows.
      dt2.Rows.Add(ndr);
   }
}

Upvotes: 0

Yograj Gupta
Yograj Gupta

Reputation: 9869

change dt2.Rows.Add(dr); to dt2.Rows.Add(dr.ItemArray);

Upvotes: 5

Related Questions