Reputation: 7
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
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:
Upvotes: 0