某人如何从数据库表中选择数据到树视图控件VB.NET?

问题描述 投票:-1回答:1

VB.NET我有下表包含数据,如下图所示:

enter image description here

现在,我想将这些数据带入树视图控件中,如其他图片所示:

enter image description here

请,如何在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

'''''''''''''''''''''''''''''''''''''''''''''''' ''''''''''''''''''''''''

vb.net treeview
1个回答
0
投票

[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

    ...
© www.soinside.com 2019 - 2024. All rights reserved.