Merging DataTables in vb.net - sql

I use vb.net to develop and I've used 5 DataTables in a windows application form and I need to combine these 5 DataTables together base on a primary key field.
To clarify
DataTable1 (PK,f1,f2,f3)
DataTable2 (PK,f4,f5,f6)
DataTable3 (PK,f7)
DataTable4 (PK,f8)
DataTable5 (PK,f9)
I need to have :
DataTable (pk,f1,f2,f3,f4,f5,f6,f7,f8,f9 )

Add a reference to System.Data.DataSetExtensions to your project,
Then you can perform a UNION on the tables like this:
Dim dt As DataTable
Dim dt2 As DataTable
Dim result = dt.AsEnumerable().Union(dt2.AsEnumerable())

Related

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:
Date|AA|AA2|AA3|AA4|AA5|AA6|
Table2:
Date|BB|BB2|BB3|BB4|BB5|BB6|
Result:
Date|AA|AA2|AA3|AA4|AA5|AA6|BB|BB2|BB3|BB4|BB5|BB6|
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:

Filter and Merge Dataset in Vb.Net

I am working on VS 2010 - Vb.Net, Having a syntax clarification on Filter & Merge DataSet
My dataset - ds has 23 tables. In which, i need to filter one Table with certain criteria.
tempDs.Merge(ds.Tables("p_tree_categories").Select( "GROUP_CODE <> 'PA.43.948'"))
On writing Merge Syntax,
I am able to see only selected table : p_tree_categories in the tempDs. We need the remaining 22 tables along with the filtered record of p_tree_categories.
How can i achieve this ?
It sounds like you only want the filtered rows of table p_tree_categories. This being the case, I would:
Generate a copy of the p_tree_categories which only contains the rows you are interested in.
Remove the existing p_tree_categories from tempDs.
Merge the copy into tempDs as p_tree_categories.
These steps could be implemented something like this:
Dim originalTable As DataTable = tempDs.Tables("p_tree_categories")
Dim filterView As DataView = New DataView(originalTable)
filterView.RowFilter = "GROUP_CODE <> 'PA.43.948'"
Dim filteredTable As DataTable = filterView.ToTable
filteredTable.TableName = "p_tree_categories"
' Remove old, add the new.
tempDs.Tables.Remove(originalTable)
tempDs.Tables.Add(filteredTable)

How to inner join two already filled DataTables in VB.NET

I marked Der Golem's answer as correct as it was the right answer for the specific problem I said I was having.
Unfortunately, I failed to detect the fact that the records in datatable2 aren't unique, which obviously doesn't jive well with performing an "inner join" on the two tables for the result I was wanting.
Setting a DataRelation would work if it was.
I'm still new to VB.NET, so please bear with me.
I have two data tables, each filled from different database servers.
They both have three columns (for ease of testing, final program will have 50+).
They both have a common data column that I want to inner join by ("OrderNum").
There's a question here, but the "answer" doesn't work for me, nor the LINQ option below it:
Merging 2 data tables in vb.net
This is my example code:
DB1 = New DatabaseConnectionSQL1
DB1.OpenConn()
DB2 = New DB_DatabaseConnectionSQL2
DB2.OpenConn()
Dim dtA As DataTable = New DataTable("DataTable1")
Dim dtB As DataTable = New DataTable("DataTable2")
Dim dtCombined As DataTable = New DataTable("CombinedDataTable")
dtA.Columns.Add("Order", System.Type.GetType("System.String"))
dtA.Columns.Add("Account_Number", System.Type.GetType("System.String"))
dtA.Columns.Add("Account_Name", System.Type.GetType("System.String"))
'"Order" = "Head_Order_Number"
dtB.Columns.Add("Head_Order_Number", System.Type.GetType("System.String"))
dtB.Columns.Add("Line_Number", System.Type.GetType("System.Int32"))
dtB.Columns.Add("Model", System.Type.GetType("System.String"))
dtA = DB1.GetDataTable(sQuery1)
dtB = DB2.GetDataTable(sQuery2)
'This doesn't work as it just appends the table
'dtA.Merge(dtB, True)
'I tried creating a DataSet and setting a Relation, but that kept failing
'I've tried at least 10 different things here. I'm at my wit's end.
dgvDataGrid.DataSource = dtCombined
dgvDataGrid.Refresh()
DB1.CloseConn()
DB2.CloseConn()
I noticed people in other places are suggesting using Linq. Even though I'm not familiar with it, I tried my best and kept failing.
Table A (dtA):
Order | Account_Number | Account_Name
10000 | 10000000000001 | BlahA
20000 | 10000000000002 | BlahB
30000 | 10000000000003 | BlahC
Table B (dtB):
Head_Order_Number| Line_Number | Model
10000 | 00000000034 | MD35Z
15000 | 00000000530 | MX25A
25000 | 00000024535 | P231Y
20000 | 00000027735 | A511L
30000 | 00000000910 | M232C
Final table I want combining the two (dtCombined):
Order | Account_Number | Account_Name | Line_Number | Model
10000 | 10000000000001 | BlahA | 00000000034 | MD35Z
20000 | 10000000000002 | BlahB | 00000027735 | A511L
30000 | 10000000000003 | BlahC | 00000000910 | M232C
Any help would be greatly appreciated.
I tried adding a DataRelation before and kept getting an error, but I wasn't setting something up properly. Now that I fixed that problem, I'm getting another error:
"System.ArgumentException: This constraint cannot be enabled as not all values have corresponding parent values."
dt1 = New DataTable("DataTable1")
dt1.Columns.Add("order_number", System.Type.GetType("System.String"))
dt1.Columns.Add("account_name", System.Type.GetType("System.String"))
dt2 = New DataTable("DataTable2")
dt2.Columns.Add("head_order_number", System.Type.GetType("System.String"))
dt2.Columns.Add("model", System.Type.GetType("System.String"))
Conn1.ConnectionString = sConnString1
Dim da1 As SqlDataAdapter = New SqlDataAdapter(sQuery1, Conn1)
Conn1.Open()
Conn2.ConnectionString = sConnString2
Dim da2 As SqlDataAdapter = New SqlDataAdapter(sQuery2, Conn2)
Conn2.Open()
ds = New DataSet
da1.Fill(ds, "DataTable1")
da2.Fill(ds, "DataTable2")
Dim dr As DataRelation = New DataRelation("Combined", _
ds.Tables("DataTable1").Columns("OrderNo"), _
ds.Tables("DataTable2").Columns("OrderNo"))
ds.Relations.Add(dr)
dgvDataGrid.DataSource = ds
dgvDataGrid.Refresh()
Conn1.Close()
Conn2.Close()
That error seems to make sense, as DataTable1 has 1950 total rows, while DataTable2 has over 4000, but isn't that the point of the DataRelation? It effectively inner joins the two tables so the end result should be 1950 rows?
The query you want to execute looks like this one:
Dim sql As String = "SELECT dta.*, dtB.* FROM dtA INNER JOIN dtB ON dtA.Order = dtB.Order"
Please note that the record with Order = 25000 is not part of the INNER JOIN
[EDIT]
As per your comment, I see you lack some knowldge...
So - ASSUMING you already have your db connection prepared (conn):
Dim cmd As OleDbCommand = New OleDbCommand(sql, conn)
Dim da As OleDbDataAdapter = New OleDbDataAdapter
da.SelectCommand = cmd
conn.Open()
Dim ds As DataSet = New DataSet
da.Fill(ds, "Result")
conn.Close()
dgvDataGrid.datasource = ds
ds.DataBind()
I'm assuming an OleDb Connection - But a SQL connection is really the same (replace OleDb with Sql)
[EDIT 2] You decided to make me sweat!
Finally, there's a solution for your very specific problem:
As shown here: http://msdn.microsoft.com/en-us/library/cc188919.aspx
The DataRelation object is what you need.
Creating DataRelation Objects
' Create the DataRelation and
' relate the customers to their orders
DataRelation oDr_Customer2Order = new DataRelation("Customer2Order",
oDs.Tables["Customer"].Columns["CustomerID"],
oDs.Tables["Order"].Columns["CustomerID"]);
oDs.Relations.Add(oDr_Customer2Order);
By creating the DataRelation objects and then adding them to the DataSet's Relations collection, the three DataTable objects' rowsets are related to one another through the defined fields. Like most of the ADO.NET objects, the DataRelation object has several different constructors. I used the constructor that accepts the name of the relation, the parent table's column, and the child table's column. If there were multiple columns that define the relationship, I could have passed in an array of the parent table's columns and an array of the child table's columns. Another option is to use the same first three parameters that I used in Figure 3 and then pass in a fourth parameter to represent whether the constraints should be created automatically (pass in a Boolean value). But more on constraints in a moment.
Once the DataSet is filled with the three rowsets and the relations are established linking the DataTable objects, the DataSet could easily be displayed in a DataGrid on a Web Form by setting the DataSource property like this:
dataGrid1.DataSource = oDs;
The DataGrid is clever enough to figure out that there are multiple DataTable objects that need to be displayed and that it should allow the rowsets to be navigated in the order that's prescribed by the DataRelation objects.

Insert To Database Table With Bindingsource / DataAdapter / Dataset (Vb.NET)

Condition :
I have 2 tables HISTORY1 and HISTORY2, those tables has the same columns but different data.
And i'm using these code below to retrieve data from database to bindingsource
dim da =new sqldataadapter
dim ds =new dataset
dim bs =new bindingsource
dim bs2 = new bindingsource
da.SelectCommand = "select * from HISTORY1"
da.fill(ds,"HISTORY1")
bs.datasource=ds.tables("HISTORY1")
And Then i add another table to bs2
da.selectcommand="select*from HISTORY2"
da.fill(ds,"HISTORY2")
bs2.datasource=ds.tables("HISTORY2")
Problem :
Now, i want to copy every single data from HISTORY2 to HISTORY1 table.
Question :
Can i update HISTORY1 from bs2?
Is there any easier way to retrieve data from database to bindingsource?
You should find what you want by searching "DataTable Merge"
here's a link on how to do it : http://vb.net-informations.com/dataset/dataset-merge-tables-sqlserver.htm
How it works :
Fill your dataTable With History1 like usual.
Change your select command to get the same table structure from your second table (History2),
Fill Again, the same dataSet but an other Table.
myDataSet.Tables(0).merge(myDataSet.Tables(1))
TADA!

Move a row from one gridview to another

I'm not sure how to go about this. Currently, in the first gridview, is a list of groups a member has access to. The second gridview is bound to a table that contains a list of every type of group and has an Add button which adds it to the first gridview and updates a table adding that group to a member.
This is what I am trying to do:
When the Add button (in the second gridview) for a row is clicked, it will be added to the first one (like it currently does), but I would also like it to disappear from the second gridview. So basically, a group should only be visible in either the first gridview or the second, not both. The problem I have is I don't want to modify the table because obviously the table contains all possible groups. Any suggestions?
I would do all the work on the database side. Data source for first one is:
Select g.*
From membership m
inner join groups g on m.groupid=g.groupid
Where m.userid = #userid
Data source for the second one looks like
Select g.*
From groups g
Where not exists
(Select 1 from membership m
Where m.GroupID=g.GroupID and m.userid = #userid
Then your add button inserts the appropriate row in the table and requeries both grids.
You could simply make changes to the Dataset, then .AcceptChanges and re-bind. This would ensure the data would update on the screen without actually pushing it to the database.
Pseudo example:
Dim dt as Datatable = GetData1(strSQL.toString)
Dim dt2 as Datatable = GetData2(strSQL.toString)
Public Sub MoveRecord(ByVal dt1 as DataTable, ByVal dt2 as Datatable, ByVal index as Integer)
'Record being moved '
Dim dr as Datarow = dt.Rows(index)
dt2.Rows.Add(dr)
dt2.AcceptChanges
dt.Rows.RemoveAt(index)
dt.AcceptChanges
'Bind Gridview
Perhaps store new changes in Viewstate,
Cache, or Session for Paging, Sorting'
End Sub
Of course, this assumes the grids have the same fields. If they don't, you'd have to:
Dim drN as DataRow - dt2.Rows.NewRow
'Assign rows from moving datarow to new datarow'
dt2.Rows.Add(drN)
dt2.AcceptChanges