MuthuKumar
MuthuKumar

Reputation: 7

Add two datatable with unique columns

I have two datatables dt1 have Id countryID dt2 have Url and Id

i want to add these two databales if i use

foreach (DataColumn col in dt.Columns)
{
    dt1.Columns.Add(col.ColumnName, col.DataType);
}

getting error like column Url already belongs to another datable please help me how to add these two tables

Upvotes: 0

Views: 92

Answers (2)

sloth
sloth

Reputation: 101162

If your goal is to create a single DataTable with three columns (Id, CountryId and Url), just create a primary key on each Id column, and simply call dt1.Merge(dt2).

Example:

var dt1 = new DataTable();
var id1 = dt1.Columns.Add("Id");
dt1.Columns.Add("CountryId");
dt1.PrimaryKey = new []{id1};
dt1.Rows.Add(new []{"1", "Austria"});
dt1.Rows.Add(new []{"2", "Iceland"});

var dt2 = new DataTable();
var id2 = dt2.Columns.Add("Id");
dt2.Columns.Add("Url");
dt2.PrimaryKey = new []{id2};
dt2.Rows.Add(new []{"1", "www.austria.at"});
dt2.Rows.Add(new []{"2", "www.iceland.is"});

dt1.Merge(dt2);

dt1 now looks like:

enter image description here

Upvotes: 0

Sadique
Sadique

Reputation: 22851

You need to copy the properties like ColumnName and create new DataColumns

You get this error because DataTable holds a reference to their columns and every column holds a reference to it's DataTable.

Upvotes: 1

Related Questions