borkowij
borkowij

Reputation: 182

Datatable.Merge doesn't work

DataTable Table = CreateTableStucture();
DataTable Table_2 = Table.Clone();
Table.Rows.Add(0, "A", "B");
Table_2.Rows.Add(0, DBNull.Value, DBNull.Value, "C");
Table.Merge(Table_2);

Why after executing this code object:Table has row with values just from Table_2 and it's not merged as it should. These tables must have the same structure because my program requires it.

EDIT 1.

    DataTable Table = new DataTable("table");
    DataColumn KeyCol = new DataColumn("Key", typeof(int));
    DataColumn Col1 = new DataColumn("col1", typeof(string));
    DataColumn Col2 = new DataColumn("col2", typeof(string));
    DataColumn Col3 = new DataColumn("col3", typeof(string));
    DataColumn Col4 = new DataColumn("col4", typeof(string));
    DataColumn Col5 = new DataColumn("col5", typeof(string));
    Table.Columns.Add(KeyCol);
    Table.Columns.Add(Col1);
    Table.Columns.Add(Col2);
    Table.Columns.Add(Col3);
    Table.Columns.Add(Col4);
    Table.Columns.Add(Col5);
    Table.Constraints.Add("keyCon", KeyCol, true);
    DataTable Table_2 = new DataTable();
    Table_2 = Table.Clone();
    Table.Rows.Add(0, "A", "B");
    Table_2.Rows.Add(0, DBNull.Value, DBNull.Value, "C");
    Table.Merge(Table_2);

Even that I create them this way it doesn't work.

Upvotes: 0

Views: 3460

Answers (2)

Scott Chamberlain
Scott Chamberlain

Reputation: 127573

The problem is you are having a primary key conflict.

DataColumn KeyCol = new DataColumn("Key", typeof(int));
//...
Table.Constraints.Add("keyCon", KeyCol, true);
//...
Table.Rows.Add(0, "A", "B");
Table_2.Rows.Add(0, DBNull.Value, DBNull.Value, "C");

You have a primary key of 0 for both rows, change the 2nd row to 1 and it should work.

Upvotes: 3

Kevin Anderson
Kevin Anderson

Reputation: 589

You need to use Table.Copy() instead of Data.Clone()

From MSDN:

DataTable.Copy Copies both the structure and data for this DataTable.

DataTable.Clone Clones the structure of the DataTable, including all DataTable schemas and constraints.

Upvotes: 1

Related Questions