Creating datatable from 2 datatables created at runtime VB.net

I have a pretty long code which creates two datatables and fills them with data at runtime. And i need to create one table, but not the way merge does it but like adding columns from one datatable as new columns(but filled with data) to the other one. Best example i can thing of is Join in SQL but i will try to draw some example. I can not put my code here as i said it't too long.

Example: (only column names but imagine that under each |something| is a lot of rows)

Table1:

Table2:

Result:

Date|AA|AA2|AA3|AA4|AA5|AA6|BB|BB2|BB3|BB4|BB5|BB6|

Upvotes: 0

Views: 845

Answers (1)

TnTinMn
TnTinMn

Reputation: 11801

The DataTable.Merge method is perfectly capable of yielding your desired result. As your two tables have only one column in common Date, I am assuming that it is PrimaryKey of at least Table 1.

Dim dt1 As New DataTable
Dim pk As DataColumn = dt1.Columns.Add("Date", GetType(DateTime))
dt1.PrimaryKey = {pk}

dt1.Columns.Add("C1")
dt1.Columns.Add("C2")
dt1.Rows.Add(#1/1/2018#, "c1", "c2")

Dim dt2 As New DataTable
Dim pk2 As DataColumn = dt2.Columns.Add("Date", GetType(DateTime))

dt2.Columns.Add("C3")
dt2.Columns.Add("C4")
dt2.Rows.Add(#1/1/2018#, "c3", "c4")
dt2.Rows.Add(#1/2/2018#, "c3a", "c4a")

Dim dt3 As DataTable = dt1.Copy
dt3.Merge(dt2)
DataGridView1.DataSource = dt3

This code yield this result:

enter image description here

Upvotes: 1

Related Questions