VB.NET我有下表包含数据,如下图所示:
现在,我想将这些数据带入树视图控件中,如其他图片所示:
请,如何在VB.NET中做到这一点?'''''''''''''''''''''''''''''''''''''''''''''''' ''''''''''''''''''这是我最终得到的代码:
Sub LoadTree()
Dim sql As String = "SELECT Employees.EmpNum , Employees.EmpName , departments.depNum, departments.depName, Company.ID, Company.CompName FROM Company INNER JOIN departments ON Company.ID = departments.compNum INNER JOIN Employees ON departments.depNum = Employees.depNum order by company.compName , departments.depName "
Dim dt As New DataTable()
Dim da As New SqlDataAdapter(sql, FrmMain.con)
da.Fill(dt)
TreeView1.Nodes.Clear()
Dim CompanyName As String
Dim depName As String
Dim EmpName As String
Dim tmpCName As String = ""
Dim tmpDName As String = ""
Dim sNode As New TreeNode
Dim ssNode As New TreeNode
'TreeView1.Nodes.Add("Dhafer")
For Each dr As DataRow In dt.Rows
CompanyName = dr("CompName").ToString()
depName = dr("depName").ToString()
EmpName = dr("EmpName").ToString()
If tmpCName = CompanyName Then
If tmpDName <> depName Then
TreeView1.SelectedNode.Nodes.Add(depName).Nodes.Add(EmpName)
End If
Else
tmpCName = CompanyName
tmpDName = depName
sNode = TreeView1.Nodes.Add(CompanyName)
TreeView1.SelectedNode = sNode
TreeView1.SelectedNode.Nodes.Add(depName).Nodes.Add(EmpName)
End If
'''''''''''''''''''''''''''''''''''''''''''''''' ''''''''''''''''''''''''
[TreeNodes具有Name属性,并且TreeNodeCollection(treeview.Nodes是什么)可以find nodes based on the Name,因此您的逻辑需要更像是:
For Each dr As DataRow In dt.Rows
Dim companyName = dr("CompName").ToString()
Dim depName = dr("depName").ToString()
Dim empName = dr("EmpName").ToString()
Dim coNodeId = "co" & Convert.ToInt32((dr("ID"))
Dim depNodeId = "dep" & Convert.ToInt32(dr("depNum"))
'find or create the company node
Dim nodes = treeview.Nodes.Find(coNodeId, true)
Dim coNode as TreeNode
If nodes.Length = 0 Then
coNode = New TreeNode() { Name = coNodeId, Text = companyName }
treeview.Nodes.Add(coNode)
Else
coNode = nodes(0)
End If
'find or create the dep node
nodes = coNode.Nodes.Find(depNodeId, true)
Dim depNode as TreeNode
If nodes.Length = 0 Then
depNode = New TreeNode() { Name = depNodeId, Text = depName }
coNode.Nodes.Add(depNode)
Else
depNode = nodes(0)
End If
'create the emp node
...