How to copy rows from a DataTable to another DataTable WITHOUT deleting existing rows?

1.8k Views Asked by At

How can I copy rows from one DataTable to another? Using DataTable.Copy() is not an option since this creates a NEW DataTable and deletes any existing DataRows. What I'm trying to do is add rows in a List<DataTable> to another table. Is there some method available that is able to do this? Or is iterating through all tables and rows and calling DataTable.ImportRow() my only option?

[UPDATE] Ok, this is the full scenario. I have a DataTable with 2 million+ records. Loading it throws System.OutOfMemoryException. So, I decided I need to page/batch load it. I'm creating the destination table using DataAdapter.FillSchema() for the purpose of loading only the columns. After that, I get the 'full records' using DataAdapter.Fill() (another DataTable), then split it into a List<DataTable>. When using DataTable.Merge, this exception is thrown: "Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints."

1

There are 1 best solutions below

0
shanmugharaj On

I tried merge as Michael said with the following code and its working for me.

DataTable table = new DataTable();
table.Columns.Add("Name");
table.Columns.Add("Address");

table.Rows.Add("Shan", "ADC Street");

DataTable table2 = new DataTable();
table2.Columns.Add("Name");
table2.Columns.Add("Address");
table2.Rows.Add("Raj", "EFG Street");

table2.Merge(table,true);

Console.WriteLine(table2.Rows.Count);      //2
Console.WriteLine(table2.Rows[0]["Name"]); //Raj
Console.WriteLine(table2.Rows[1]["Name"]); //Shan