0

I have a datatable in which some rows needed to be copied to a new datatable on some condition.My statements are as below.

dt1 = ds1.Tables[0];
DataRow[] dRows = dt1.Select("IS_ALLOWED=" + false);
for (int i = 0; i < dRows.Length; i++)
{
   dtPerm.Rows.Add(dRows[i]);  //------(1)   
   //dtPerm.ImportRow(dRows[i]);  //------(2)   
}

But while debugging from ------(1). It jumps to catch. The exception is

"This row already belongs to another table."

The ----(2) doesn't making any error and the Rows are not adding,But the row is empty and only have a single column.

Is there any solution for this.

Arvin
  • 954
  • 3
  • 14
  • 33
  • Have a look at: http://stackoverflow.com/a/4020284/1134076 – Dr Schizo Aug 04 '14 at 10:45
  • possible duplicate of [copy rows from Datatable to another Datatable c#](http://stackoverflow.com/questions/4020270/copy-rows-from-datatable-to-another-datatable-c-sharp) – Arion Aug 04 '14 at 10:53

2 Answers2

1

Modify the for loop to something like this :

 foreach (DataRow row in dRows)
   {
       dtPerm.ImportRow(row);
   }

And before adding the rows to the DataTable, make sure you have made the columns to store the row values. See this code :

 DataTable dtPerm = new DataTable();
 dtPerm.Columns.Add("Column1");
 dtPerm.Columns.Add("Column2");
 dtPerm.Columns.Add("Column3");
 dtPerm.Columns.Add("Column4");
 dtPerm.Columns.Add("Column5");

After this, place the above shown for loop and this will work just fine.

Hope this helps.

Dhrumil
  • 3,221
  • 6
  • 21
  • 34
  • Thank you.. I think it is possible to use dtTarget=dtSource.Clone() instead of the statements you added – Arvin Aug 04 '14 at 11:22
  • Probably. I added them just in case if you forgot to do that and because of it you received that error. :) – Dhrumil Aug 04 '14 at 11:25
0

Thank you all. I added a statement above the loop starts and modified the code inside the loop and it is working fine now

dt1 = ds1.Tables[0];
dtPerm = dt1.Clone();
DataRow[] dRows = dt1.Select("IS_ALLOWED=" + false);
for (int i = 0; i < dRows.Length; i++)
{
   dtPerm.ImportRow(dRows[i]);  //------(2)   
}
Arvin
  • 954
  • 3
  • 14
  • 33