Populating a treeview with two tables using vb.net - vb.net

Hello I have this two tables:
Then I want this result using treeview:
id department category
1 MIS System
1 MIS Networking
1 MIS Programmer
2 Audit Operations
2 Audit DS
3 HRD PA
3 HRD PayBen
3
HRD PS
3 HRD PLD
4 Acounting Sup
4 Acounting FMCG
5 Procurement NULL
or like this
MIS
-System
-Networking
-Programmer
AUDIT
-Operations
-DS
HRD
-PA
-PayBen
-PS
-PLD
Acounting
-Sup
-FMCG
Can someone please guide me, thank you. I'm having trouble finding any solution on the internet and I'm new to the vb.net language.

In my code below, i give you the logic. You just need to query your tables now.
Tell me if you need explanations.
TreeView1.Nodes.Clear()
'Create a first node and select it
Dim root As TreeNode = TreeView1.Nodes.Add("Test")
TreeView1.SelectedNode = root
'Create two types of node
Dim department As New TreeNode()
Dim category As New TreeNode()
'Daos (if you create a Department class and subDepartment class)
Dim _daoD As New Departments(_cnx)
Dim _daoSD As New subDepartments(_cnx)
'Lists (depending on classes too)
Dim listD As List(Of Department)
Dim listSD As List(Of subDepatment)
For Each dep As Department In listD
'Add a Tree node for a new department
department = New TreeNode(dep.department)
department.Tag = dep.id
root.Nodes.Add(department)
TreeView1.SelectedNode = departement
For Each subDep As subDepartment In listSubDep
'Add a TreeNode for new categories
categ = New TreeNode(subDep.category)
categ.Tag = subDep.id
Nodes.Add(categ)
Next
Next
Then, you can create 4 classes (the first one with properties, and the second one to query in the table)
Public Class Department
'properties
Public Property id As Integer
Get
Return _ID
End Get
Set(ByVal Value As Integer)
_ID = Value
End Set
End Property
'etc
End Class
Public Class Departments
Dim _cnx As OracleConnection (if you use Oracle)
Public Sub New(ByVal pcnx As OracleConnection)
_cnx = pcnx
End Sub
'Your queries
End Class

Here is my solutio. i hope this will help someone who have this kind of problem.
Dim myConnString As String = "Data Source=name;Initial Catalog=database;Integrated Security=True"
Dim daMyName As New SqlDataAdapter
Dim dsMyName As New DataSet
Dim recCount As Integer
Dim mySelectQuery As String = "SELECT DEPARTMENT.department, subDept.category from subdept right join department on .department.id = subDept.parent"
Dim myConnection As New SqlConnection(myConnString)
Dim myCommand As New SqlCommand(mySelectQuery, myConnection)
myConnection.Open()
daMyName.SelectCommand = myCommand
daMyName.Fill(dsMyName)
Dim tbl As DataTable = dsMyName.Tables(0)
recCount = dsMyName.Tables(0).Rows.Count
tvw1.Nodes.Clear() 'Clear any nodes so we don't load a tree into a tree
Dim nd As TreeNode
nd = tvw1.Nodes.Add("DEPARTMENT")
Dim parentRow As DataRow
Dim rowNdx As Integer
rowNdx = 0
daMyName.Fill(tbl)
Dim Jan As String
For Each parentRow In tbl.Rows
If rowNdx = recCount Then
Exit For
End If
Jan = dsMyName.Tables(0).Rows(rowNdx)("Department").ToString() 'set the next name
Dim Dnode As TreeNode
Dnode = tvw1.Nodes.Add(dsMyName.Tables(0).Rows(rowNdx)("department").ToString())
Dim cnode As TreeNode
cnode = New TreeNode
Do While dsMyName.Tables(0).Rows(rowNdx)("department").ToString() = Jan And rowNdx < recCount
'if it changes we need to kick out of Do While
cnode = Dnode.Nodes.Add(dsMyName.Tables(0).Rows(rowNdx)("category").ToString())
rowNdx = rowNdx + 1
If rowNdx = recCount Then
Exit Do
End If
Loop
Next parentRow
myConnection.Close()

Related

Display SQL data in TreeView

I am showing data from 1 table from SQL Server 2018 to a TreeView. I can only show the tree up to this point
Private Sub btnPopular_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPopular.Click
Dim conexaoSQLServer As SqlConnection = Nothing
Dim cmd As SqlCommand
Dim da As New SqlDataAdapter
Dim ds As New DataSet
'DBSQLServer = "SELECT RTRIM(D.DESCRIPCION),RTRIM(P.DESCRIPCION) " +
'"FROM PROVINCIAS AS P INNER JOIN DEPARTAMENTO AS D ON P.IDDEPARTAMENTO=D.IDDEPARTAMENTO"
Dim strCon As String = "Data Source = SOPORTE-ERP\SQLEXPRESS; Initial Catalog = prueba; Integrated Security = True"
'define a consulta para obter as tabelas e suas colunas
Dim sqlConsulta As String = "SELECT RTRIM(D.DESCRIPCION),RTRIM(P.DESCRIPCION) " +
"FROM PROVINCIA AS P INNER JOIN DEPARTAMENTO AS D ON P.IDDEPARTAMENTO=D.IDDEPARTAMENTO"
'define os nodes que iremos usar no treeview
Dim NoRaiz As TreeNode = Nothing
Dim NoPrincipal As TreeNode = Nothing
Dim NoFilho As TreeNode = Nothing
Dim nieto As TreeNode = Nothing
'define algumas constanes e variaveis usadas
Dim nomePrincipal As String = String.Empty
Dim nomeFilho As String = String.Empty
Dim BancoDados As String = DBSQLServer
Try
'define e abre a conexão com o SQL Server
conexaoSQLServer = New SqlConnection(strCon)
conexaoSQLServer.Open()
'atribui o comando usado na conexão
cmd = New SqlCommand(sqlConsulta, conexaoSQLServer)
da.SelectCommand = cmd
'preenche o dataset
da.Fill(ds, "DATOS_SISTEMAS")
tvwDados.Nodes.Clear()
'inclui o node raiz
NoRaiz = tvwDados.Nodes.Add("UBIGEO")
Dim contaTabelas As Integer = 0
For Each row As DataRow In ds.Tables("DATOS_SISTEMAS").Rows
If nomePrincipal <> row(0).ToString Then
NoPrincipal = NoRaiz.Nodes.Add(row(0).ToString)
'imageIndex:=1, selectedImageIndex:=1'
nomePrincipal = row(0).ToString
contaTabelas += 1
End If
NoFilho = NoPrincipal.Nodes.Add(key:="", text:=row(1).ToString)
'nieto = NoPrincipal.Nodes.Add(key:="DISTRITOS", text:=row(2).ToString)
'imageIndex:=2, selectedImageIndex:=2
Next
lblTabelas.Text = contaTabelas.ToString & " Tabelas no arquivo"
tvwDados.Nodes(0).EnsureVisible()
Catch ex As Exception
MessageBox.Show("Erro ao realizar a operação com o arquivo : " & ex.Message)
Exit Sub
Finally
'libera os recursos da conexão usada
conexaoSQLServer.Close()
conexaoSQLServer.Dispose()
conexaoSQLServer = Nothing
End Try
End Sub
And it shows me as follows in the picture
now I want another sub-tree or item to be broken down to me where the districts are shown as follows DEPARTMENT / PROVINCE / DISTRICT
In essence, this is a data querying question.
I use these conceptual tables for my answer. I hope they reflect your actual table structure.
CREATE TABLE DEPARTAMENTO (
IDDEPARTAMENTO CHAR(2) NOT NULL,
DESCRIPCION VARCHAR(50) NOT NULL,
CONSTRAINT PK_DEPARTAMENTO PRIMARY KEY (IDDEPARTAMENTO),
CONSTRAINT UQ_DEPARTAMENTO UNIQUE (DESCRIPCION)
);
CREATE TABLE PROVINCIA (
IDDEPARTAMENTO CHAR(2) NOT NULL,
IDPROVINCIA CHAR(2) NOT NULL,
DESCRIPCION VARCHAR(50) NOT NULL,
CONSTRAINT PK_PROVINCIA PRIMARY KEY (IDDEPARTAMENTO, IDPROVINCIA),
CONSTRAINT UQ_PROVINCIA UNIQUE (IDDEPARTAMENTO, DESCRIPCION),
CONSTRAINT FK_PROVINCIA_DEPARTAMENTO FOREIGN KEY (IDDEPARTAMENTO) REFERENCES DEPARTAMENTO (IDDEPARTAMENTO)
);
CREATE TABLE UBIGEO (
IDUBIGEO CHAR(6) NOT NULL,
IDDEPARTAMENTO CHAR(2) NOT NULL,
IDPROVINCIA CHAR(2) NOT NULL,
DESCRIPCION VARCHAR(50) NOT NULL,
CONSTRAINT PK_UBIGEO PRIMARY KEY (IDUBIGEO),
CONSTRAINT UQ_UBIGEO UNIQUE (IDDEPARTAMENTO, IDPROVINCIA, DESCRIPCION),
CONSTRAINT FK_UBIGEO_PROVINCIA FOREIGN KEY (IDDEPARTAMENTO, IDPROVINCIA) REFERENCES PROVINCIA (IDDEPARTAMENTO, IDPROVINCIA)
);
Next, I would look at the data that is actually required for populating a treeview. Every node refers to a parent node (or a parent node contains several child nodes). I would like to reflect that in the data that I retrieve from the database.
Each of the above three tables holds node data. Instead of using JOINs, I would use UNIONs here, so that each row in the result data represents a single node. Each row should contain at least three fields:
nodeText will contain the node text that is displayed in the treeview's nodes
nodeKey will contain a unique textual key for the node
nodeParentKey will contain the key of the parent node (or an empty string if it has no parent)
So the query that I would execute to retrieve the node data would look something like this:
'define a consulta para obter as tabelas e suas colunas
Dim sqlConsulta As String = "
SELECT
D.DESCRIPCION AS nodeText,
'DEPA' + D.IDDEPARTAMENTO AS nodeKey,
'' AS nodeParentKey
FROM
DEPARTAMENTO AS D
UNION ALL
SELECT
P.DESCRIPCION AS nodeText,
'PROV' + P.IDDEPARTAMENTO + P.IDPROVINCIA AS nodeKey,
'DEPA' + P.IDDEPARTAMENTO AS nodeParentKey
FROM
PROVINCIA AS P
UNION ALL
SELECT
U.DESCRIPCION AS nodeText,
'DIST' + U.IDUBIGEO AS nodeKey,
'PROV' + U.IDDEPARTAMENTO + U.IDPROVINCIA AS nodeParentKey
FROM
UBIGEO AS U
"
I would rewrite the loop that processes your retrieved data and actually convert it to two loops.
The first loop processes the retrieved data and creates the TreeNode objects. But instead of immediately putting them in a Nodes collection in the tvwDados treeview, I would put them in a helper dictionary. Additionally, I would store the node's key in another helper dictionary as well. These helper dictionaries will be used in the second loop.
The second loop actually populates the tvwDados treeview from the nodes dictionary and add the node either to the tvwDados.Nodes collection or a parent node's Nodes collection, which depends if a parent key can be found in the nodeParents dictionary.
My data processing code would look something like this:
'Helper dictionaries
Dim nodes As New Dictionary(Of String, TreeNode) 'Holds the nodes based on their key values
Dim nodeParents As New Dictionary(Of String, String) 'Holds the parent keys of child nodes
'Create nodes from data
For Each row As DataRow In ds.Tables("DATOS_SISTEMAS").Rows
Dim nodeText As String = row.Field(Of String)("nodeText")
Dim nodeKey As String = row.Field(Of String)("nodeKey")
Dim nodeParentKey As String = row.Field(Of String)("nodeParentKey")
nodes.Add(nodeKey, New TreeNode(nodeText))
If Not String.IsNullOrEmpty(nodeParentKey) Then
nodeParents.Add(nodeKey, nodeParentKey)
End If
Next
'Add nodes to treeview (and resolve parents)
For Each kvp In nodes
Dim node As TreeNode = kvp.Value
Dim nodeKey As String = kvp.Key
Dim nodeParentKey As String = Nothing
If nodeParents.TryGetValue(nodeKey, nodeParentKey) Then
'Child node
Dim parentNode As TreeNode = nodes(nodeParentKey)
parentNode.Nodes.Add(node)
Else
'Root node
tvwDados.Nodes.Add(node)
End If
Next
I am not sure about the purpose of your contraTabelas integer and your NoRaiz, NoPrincipal and NoFilho tree nodes. For the sake of clarity I omitted them from my code. I assume that you will be able to include them in the processing logic yourself if you still need them.
Edit:
If you want to do special things when double clicking a district node, you can pass additional data in a node's Tag property.
In the above code, change this line:
nodes.Add(nodeKey, New TreeNode(nodeText))
to this:
Dim node As New TreeNode(nodeText)
node.Tag = nodeKey
nodes.Add(nodeKey, node)
Next, you can implement the tree view's NodeMouseDoubleClick event handler. It could look something like this:
Private Sub tvwDados_NodeMouseDoubleClick(sender As Object, e As TreeNodeMouseClickEventArgs) Handles tvwDados.NodeMouseDoubleClick
Dim nodeKey As String = TryCast(e.Node.Tag, String)
If nodeKey IsNot Nothing AndAlso nodeKey.StartsWith("DIST") Then
'You have double clicked a district node
Dim IDDISTRITO As Integer = Integer.Parse(nodeKey.Substring(4))
'Do something with the district id here
'...
End If
End Sub
If you need help with additional subjects, just feel free to post an entirely new question here on StackOverflow.
Edit:
I have updated my answer based on new information. I have made changes to the conceptual table structure and the SQL query in the sqlConsulta variable. As far as I can determine, it should not produce duplicate key errors anymore.
I think that the duplicate key errors came from the province nodes. So for the province nodes, I included both the department ID and the province ID in the node key.
the structure of my database is the same as what you are proposing, executing the query with a small change shows me as follows.
SELECT D.DESCRIPCION AS nodetext,CAST(D.IDDEPARTAMENTO AS VARCHAR) AS nodeKey,'' AS nodeParentKey
FROM DEPARTAMENTO AS D UNION ALL
SELECT P.DESCRIPCION AS nodeText,CAST(P.IDPROVINCIA AS VARCHAR) AS nodeKey,CAST(P.IDDEPARTAMENTO AS VARCHAR) AS nodeParentKey
FROM PROVINCIA AS P UNION ALL
SELECT U.DESCRIPCION AS nodeText,CAST(U.IDUBIGEO AS VARCHAR) AS nodeKey,CAST(U.IDPROVINCIA AS VARCHAR) AS nodeParentKey
FROM ubigeo AS U SELECT * FROM ubigeo
UBIGEO IS A DISTRICT
AND IT SHOWS SO
when executing the code that you published it shows me this error message
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim conexaoSQLServer As SqlConnection = Nothing
Dim cmd As SqlCommand
Dim da As New SqlDataAdapter
Dim ds As New DataSet
DBSQLServer = "prueba"
Dim strCon As String = "Data Source = DESKTOP-2IM88ST\SQLEXPRESS; Initial Catalog = " & DBSQLServer & "; Integrated Security = True"
'define a consulta para obter as tabelas e suas colunas
Dim sqlConsulta As String = "SELECT D.DESCRIPCION AS nodeText,CAST(D.IDDEPARTAMENTO AS VARCHAR) AS nodeKey,'' AS nodeParentKey FROM DEPARTAMENTO AS D UNION ALL " +
"SELECT P.DESCRIPCION AS nodeText,CAST(P.IDPROVINCIA AS VARCHAR) AS nodeKey,CAST(P.IDDEPARTAMENTO AS VARCHAR) AS nodeParentKey FROM PROVINCIA AS P UNION ALL " +
"SELECT U.DESCRIPCION AS nodeText,CAST(U.IDUBIGEO AS VARCHAR) AS nodeKey,CAST(U.IDPROVINCIA AS VARCHAR) AS nodeParentKey FROM ubigeo AS U"
Try
'define e abre a conexão com o SQL Server
conexaoSQLServer = New SqlConnection(strCon)
conexaoSQLServer.Open()
'atribui o comando usado na conexão
cmd = New SqlCommand(sqlConsulta, conexaoSQLServer)
da.SelectCommand = cmd
'preenche o dataset
da.Fill(ds, "DATOS_SISTEMAS")
'Helper dictionaries
Dim nodes As New Dictionary(Of String, TreeNode) 'Holds the nodes based on their key values
Dim nodeParents As New Dictionary(Of String, String) 'Holds the parent keys of child nodes
'Create nodes from data
TreeView1.Nodes.Clear()
For Each row As DataRow In ds.Tables("DATOS_SISTEMAS").Rows
Dim nodeText As String = row.Field(Of String)("nodeText")
Dim nodeKey As String = row.Field(Of String)("nodeKey")
Dim nodeParentKey As String = row.Field(Of String)("nodeParentKey")
nodes.Add(nodeKey, New TreeNode(nodeText))
If Not String.IsNullOrEmpty(nodeParentKey) Then
nodeParents.Add(nodeKey, nodeParentKey)
End If
Next
'Add nodes to treeview (and resolve parents)
For Each kvp In nodes
Dim node As TreeNode = kvp.Value
Dim nodeKey As String = kvp.Key
Dim nodeParentKey As String = Nothing
If nodeParents.TryGetValue(nodeKey, nodeParentKey) Then
'Child node
Dim parentNode As TreeNode = nodes(nodeParentKey)
parentNode.Nodes.Add(node)
Else
'Root node
TreeView1.Nodes.Add(node)
End If
Next
Catch ex As Exception
MessageBox.Show("Erro ao realizar a operação com o arquivo : " & ex.Message)
Exit Sub
Finally
'libera os recursos da conexão usada
conexaoSQLServer.Close()
conexaoSQLServer.Dispose()
conexaoSQLServer = Nothing
End Try
End Sub
End Class
error when performing this operation: an element with the same key has already been added
Bart Hofland,
the query to verify, it shows me this information in the new database.
this is the ubigeo or district table

value of type integer cannot be converted to datatable vn.net

i am trying to create tree view and some error i can not fix it
Sub CREATENODE()
Dim TRN As New TreeNode
Dim DT As New DataTable
DT.Clear()
DT = ACCOUNTTableAdapter.TREE_ACCOUNT()
For I As Integer = 0 To DT.Rows.Count - 1
If DT.Rows(I)(9).ToString() = "00000000-0000-0000-0000-000000000000" Then
TRN = New TreeNode(DT.Rows(I)(3).ToString() + " " + DT.Rows(I)(4).ToString())
TRN.Tag = DT.Rows(I)(1).ToString()
If DT.Rows(I)(7).ToString() <> "0" Then
TRN.ImageIndex = 0
TRN.SelectedImageIndex = 0
Else
TRN.ImageIndex = 1
TRN.SelectedImageIndex = 1
End If
TreeView1.Nodes.Add(TRN)
End If
Next
''For Each NODE As TreeNode In TreeView1.Nodes
'' CHELD(NODE)
'Next
End Sub
This is nonsense
Dim TRN As New TreeNode
Dim DT As New DataTable
DT.Clear()
DT = ACCOUNTTableAdapter.TREE_ACCOUNT()
You create a New TreeNode and then inside the loop you overwrite it with another New one. Just put the Dim inside the loop after the if.
Dim TRN = New TreeNode($"{row(3)} {row(4)}")
You create a brand new DataTable. Then you clear it when it can't possibly have anything in it. Then you throw it away and assign a different DataTable to it.
Just do
Dim DT = ACCOUNTTableAdapter.TREE_ACCOUNT()
I have simplified your code by using a For Each loop. Also, I used and interpolated string indicated by the $ preceding the string. Variables can be inserted in place surrounded by braces { }.
As far as the actual problem, you need to create an instance of your table adapter with the New keyword. Then call the appropriate method. A simple application will just use .GetData.
Private Sub CREATENODE()
Dim DT = (New ACCOUNTTableAdapter).TREE_ACCOUNT() 'See what intellisense offers. It may be just .GetData
For Each row As DataRow In DT.Rows
If row(9).ToString() = "00000000-0000-0000-0000-000000000000" Then
Dim TRN = New TreeNode($"{row(3)} {row(4)}")
TRN.Tag = row(1)
If row(7).ToString() <> "0" Then
TRN.ImageIndex = 0
TRN.SelectedImageIndex = 0
Else
TRN.ImageIndex = 1
TRN.SelectedImageIndex = 1
End If
TreeView1.Nodes.Add(TRN)
End If
Next
End Sub
Hint: Why not put the entire row in the Tag property. You will have access to all the fields by casting the Tag back to a DataRow.

How to put data of MS excel of one column inside array in vb.net

I have data on my MS.Excel spreadsheet which contain different column (Sn , Amount and tech id). I am trying to put all the data of tech id on tech id in array like :-
mydata = [43219 , 43220 , 43221 , 43222 ,43223 ,43224 , 43225 ]
My code of only one main processing function:-
Importing :-
Imports System.IO
Imports System.Data.OleDb
main processing function:-
Dim conString1 As String
Dim Mydata(200) As Integer
Dim connection As OleDbConnection
Dim adapter As OleDbDataAdapter
Private Sub LoadData(conStr As String)
con = New OleDbConnection(conStr)
Dim query As String = "SELECT * FROM [Sheet0$]"
adapter = New oleDbDataAdapter(query, connection)
'Putting data indide array
'For intCount = 0 To lengthofcolumn
'Mydata(intCount) = ?
'Next intCount
Debug.Print(adapter)
End Sub
Calling :-
conString1 = String.Format("Provider = Microsoft.Jet.OLEDB.4.0;Data Source = '{0}'; Extended Properties = Excel 8.0", 'F:\MicroTest\data\log.xlsx)')
LoadData(conString1)
I am a student , I am learning so please help ,I did't find this solution , Mostly I found solution of viewing excel data in datagrid
My test data was in B2:B8.
You will need to add the Reference: Microsoft Excel 14.0 Object Library
Dim oExcel As New Microsoft.Office.Interop.Excel.Application
oExcel.Workbooks.Open("C:\TEMP\test_data.xlsx")
Dim oSheet As Microsoft.Office.Interop.Excel.Worksheet = oExcel.Sheets(1)
' I would use list instead of an array.
Dim oTest As New List(Of String)
For Each oValue As String In oSheet.Range("B2:B8").Value2
oTest.Add(oValue)
Next
' Using an array
Dim oData(200) As Integer
Dim iCounter As Integer = 0
For Each oValue As String In oSheet.Range("B2:B8").Value2
oData(iCounter) = CType(oValue, Integer)
iCounter += 1
Next
oExcel.Quit()
I think your approach is good, accessing the file with OleDB and not openning an instance of Excel.
I used a DataReader and DataTable to collect and hold the data in memory.
The Using...End Using blocks ensure your objects that have a Dispose method are closed and disposed properly even if there is an error.
Private Sub LoadData()
Dim dt As New DataTable()
Dim conStr As String = "Your connection string"
Using con As New OleDbConnection(conStr)
Dim query As String = "SELECT * FROM [Sheet1$]"
Using cmd As New OleDbCommand(query, con)
con.Open()
Using dr As OleDbDataReader = cmd.ExecuteReader()
dt.Load(dr)
End Using
End Using
End Using
'The number of rows in the DataTable less the first 2 rows which are title and blank
'and subtract 1 because vb.net arrays are defined array(upper bound)
Dim arraySize As Integer = dt.Rows.Count - 3
Dim myData(arraySize) As Integer
Dim arrayIndex As Integer = 0
'Putting data indide array
For rowIndex As Integer = 2 To dt.Rows.Count - 1
myData(arrayIndex) = CInt(dt.Rows(rowIndex)(3)) '3 is the index of the TechID column
arrayIndex += 1
Next
'Checking the array - delete in final version
'I used i as a variable name because this is a very tiny
'loop and will be deleted eventually. Otherwise, I would
'have used a more descriptive name.
For Each i As Integer In myData
Debug.Print(i.ToString)
Next
End Sub

how to Flip dataset and display in datagridview

I try to flip dataset to display column as rows by using this code but it does not work :
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button.Click
Dim ds2 As New DataSet
Dim dt2 As New DataTable
Dim com1 As String = "select col1,col2,col3 from table1"
ds2 = FlipDataSet(ds2)
Dim dp As New SqlDataAdapter(com1, conn)
dp.Fill(dt2)
DGV_lev1.DataSource = dt2.DefaultView
End Sub
and use this function to flip dataset :
Private Function FlipDataSet(old_DataSet As DataSet) As DataSet
Dim ds As New DataSet()
For Each dt As DataTable In old_DataSet.Tables
Dim table As New DataTable()
For i As Integer = 0 To dt.Rows.Count
table.Columns.Add(Convert.ToString(i))
table.Columns(0).ColumnName = "Fields"
If i = 0 Then
Continue For
Else
table.Columns(i).ColumnName = "Customer " & i
End If
Next
Dim r As DataRow
For k As Integer = 0 To dt.Columns.Count - 1
r = table.NewRow()
r(0) = dt.Columns(k).ToString()
For j As Integer = 1 To dt.Rows.Count
r(j) = dt.Rows(j - 1)(k)
Next
table.Rows.Add(r)
Next
ds.Tables.Add(table)
Next
Return ds
End Function
to make datagirdview display from this :
to this :
can anyone help me
thank you
Try this, it worked in a quick test I did:
Private Function Transpose(ByVal table As DataTable) As DataTable
Dim flippedTable As New DataTable
'creates as many columns as rows in source table
flippedTable.Columns.AddRange(
table.Select.Select(
Function(dr) New DataColumn("col" & table.Rows.IndexOf(dr), GetType(Object))
).ToArray)
'iterates columns in source table
For Each dc As DataColumn In table.Columns
'get array of values of column in each row and add as new row in target table
flippedTable.Rows.Add(table.Select.Select(Function(dr) dr(dc)).ToArray)
Next
Return flippedTable
End Function

Join two queries from different data sources using VB.NET

I have two queries. One is an Oracle query, and one is a SQL Server query.
Oracle Columns: ID, Subject, Course
SQL Server Columns: ID, Recommended Subject, Recommended Course
I would like to join the two queries on ID. I need to find out which IDs have a subject that is not equal to the recommended subject or a course that is not equal to the recommended course. Then, display the results in a GridView.
Here's what I have tried to do so far. I have removed my SQL commands and connection strings.
Dim sConnectionString As String = ConfigurationManager.ConnectionStrings("sqlserver").ConnectionString
Dim sCN As New SqlConnection(sConnectionString)
Dim sCommandWrapper As SqlCommand = New SqlCommand("SQL", sCN)
Dim sDataAdapter As SqlDataAdapter = New SqlDataAdapter
sDataAdapter.SelectCommand = sCommandWrapper
Dim pConnectionString As String = ConfigurationManager.ConnectionStrings("oracle").ConnectionString
Dim pCN As New OleDbConnection(pConnectionString)
Dim pCommandWrapper As OleDbCommand = New OleDbCommand("SQL", pCN)
Dim pDataAdapter As OleDbDataAdapter = New OleDbDataAdapter
pDataAdapter.SelectCommand = pCommandWrapper
Dim stopDS As DataSet = New DataSet()
sDataAdapter.Fill(stopDS, "Recommendations")
pDataAdapter.Fill(stopDS, "Registrations")
Since you have your two results in a DataSet, you can define a relationship between the two tables using the DataSet.Relations property:
stopDS.Relations.Add(
"ID2ID",
stopDS.Tables("Recommendations").Columns("ID"),
stopDS.Tables("Registrations").Columns("ID")
)
You can then get the matching rows from either end of the relationship (apologies if I got the relationship the wrong way around!):
Dim rows() As DataRow = stopDS.Tables("Recommendations").Rows(0).GetChildRows("ID2ID")
Dim row As DataRow = stopDS.Tables("Registrations").Rows(0).GetParentRow("ID2ID")
' Can also use .GetParentRows(...) for an array.
Here is a complete example console app:
Module Module1
Sub Main()
Dim t1 = New DataTable()
t1.TableName = "Names"
t1.Columns.Add("ID", GetType(Integer))
t1.Columns.Add("Name", GetType(String))
Dim t2 = New DataTable()
t2.TableName = "Addresses"
t2.Columns.Add("ID", GetType(Integer))
t2.Columns.Add("Address", GetType(String))
Dim r As DataRow = Nothing
r = t1.NewRow()
r("ID") = 1
r("Name") = "Bob"
t1.Rows.Add(r)
r = t1.NewRow()
r("ID") = 2
r("Name") = "Joe"
t1.Rows.Add(r)
r = t1.NewRow()
r("ID") = 3
r("Name") = "Sue"
t1.Rows.Add(r)
r = t2.NewRow()
r("ID") = 1
r("Address") = "1 Main St"
t2.Rows.Add(r)
r = t2.NewRow()
r("ID") = 3
r("Address") = "2 Any St"
t2.Rows.Add(r)
Dim ds = New DataSet()
ds.Tables.Add(t1)
ds.Tables.Add(t2)
' Define relationship between the ID columns
ds.Relations.Add(
"NameToAddress",
ds.Tables("Names").Columns("ID"),
ds.Tables("Addresses").Columns("ID"))
For Each nameRow In t1.AsEnumerable()
Console.WriteLine("Name: {0}", nameRow.Field(Of String)("Name"))
For Each addrRow In nameRow.GetChildRows("NameToAddress")
Console.WriteLine("--Addr: {0}", addrRow.Field(Of String)("Address"))
Next
Next
Console.WriteLine("==========")
For Each addrRow In t2.AsEnumerable()
Console.WriteLine("Addr: {0}", addrRow.Field(Of String)("Address"))
Dim pr = addrRow.GetParentRow("NameToAddress")
If pr IsNot Nothing Then
Console.WriteLine("++Name: {0}", pr.Field(Of String)("Name"))
End If
For Each nameRow In addrRow.GetParentRows("NameToAddress")
Console.WriteLine("--Name: {0}", nameRow.Field(Of String)("Name"))
Next
Next
Console.ReadLine()
End Sub
End Module
The results are:
Name: Bob
--Addr: 1 Main St
Name: Joe
Name: Sue
--Addr: 2 Any St
==========
Addr: 1 Main St
++Name: Bob
--Name: Bob
Addr: 2 Any St
++Name: Sue
--Name: Sue
I really like Mike's approach, but let me suggest another one and you can choose whichever more suitable for you.
You can set up a linked server to your Oracle database. It is described in this answer. Alternatively you can follow this article.
Then simply join the two tables and get the results:
SELECT * FROM SqlTable s
INNER JOIN OracleServer.OracleDB..OracleTable o ON o.ID = s.ID
AND (s.Course != o.[Recommended Course] OR s.Subject != o.[Recommended Subject])
Unfortunately I don't have oracle installed to completely test this myself, but I hope you get in the direction.