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
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().
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.
Use
newtable.ImportRow(oldtable.Rows[i])
where i
is the desired row number.
as explained in http://support.microsoft.com/kb/308909/en-us
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With