Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

copy a single row from one datatable to other

I have two datatables one has few rows other is empty. I am running a loop over first one to copy some of the rows to another table. I am getting error 'The row already belongs to another table'.

Is there any way to copy DataRows one by one to other DataTable.

thanks in advance

like image 846
MaxRecursion Avatar asked Apr 26 '12 08:04

MaxRecursion


People also ask

How do I copy DataTable from one DataTable to another?

Copy() creates a new DataTable with the same structure and data as the original DataTable. To copy the structure to a new DataTable, but not the data, use Clone().

What is imported row?

Calling NewRow adds a row to the table using the existing table schema, but with default values for the row, and sets the DataRowState to Detached . Calling ImportRow preserves the existing DataRowState along with other values in the row.


2 Answers

Use

newtable.ImportRow(oldtable.Rows[i]) 

where i is the desired row number.

as explained in http://support.microsoft.com/kb/308909/en-us

like image 132
Nikhil Agrawal Avatar answered Sep 25 '22 19:09

Nikhil Agrawal


copy the ItemArray, of course just works when the columns are the same

var dtCopyTo = new DataTable();
foreach(var rowCopyFrom in dtCopyFrom.Rows)
{
    var updatedDataRow = dtCopyTo.NewRow();
    updatedDataRow.ItemArray = rowCopyFrom.ItemArray;
    dtCopyTo.AddRow(updatedDataRow);
}

ps: code is typed without ide so check syntax pls

like image 29
blindmeis Avatar answered Sep 23 '22 19:09

blindmeis