VB.NET从treevew复制数据到datagridview

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

我想把所有数据从树视图复制到数据网格视图中,例如:如果我选择了一个部门或公司的一个节点,当我点击一个按钮时,我想把该节点的所有员工复制到数据网格视图中,并检查是否重复。

谁能给我解释一下这个机制。

这是我想写的代码,但我很难做到这一点

For i = 0 To TreeView1.Nodes.Count - 1
        'MsgBox(i & " " & TreeView1.Nodes(i).Text)
        Dim node As TreeNode = TreeView1.Nodes(i)
        For j = 0 To node.Nodes.Count - 1
            'MsgBox(j & " " & node.Nodes(j).Text)
            Dim subnode As TreeNode = node.Nodes(j)
            For z = 0 To subnode.Nodes.Count - 1
                'MsgBox(z & " " & subnode.Nodes(z).Text)
                Dim Usubnode As TreeNode = subnode.Nodes(j)
                DGV.Rows(z).Cells(0).Value = subnode.Nodes(z).Name.ToString
                DGV.Rows(z).Cells(1).Value = subnode.Nodes(z).Text.ToString
            Next  '' z
        Next   ''j
    Next  '' i

enter image description here

treeview是这样填充的。

 For Each dr As DataRow In dt.Rows
        Dim coName = dr("CompName").ToString()
        Dim coNodeId = "co" & dr("ID").ToString()

        ''''find or create the company node
        Dim nodes = TreeView2.Nodes.Find(coNodeId, True)
        Dim coNode As TreeNode

        If nodes.Length = False Then ''''didn't find: create and add
            coNode = New TreeNode()  {.Name = coNodeId, .Text = coName}
            TreeView2.Nodes.Add(coNode)

        Else ''''did find
            coNode = nodes(0)
        End If


        Dim depName = dr("depName").ToString()
        Dim depNodeId = "dep" & dr("depNum").ToString()

        ''''find or create the dep node under the co 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
        Dim EmpName = dr("EmpName").ToString()
        Dim empNodeId = "emp" & dr("EmpNum").ToString()

        ''''find or create the emp node under the dep node
        nodes = depNode.Nodes.Find(empNodeId, True)
        Dim empNode As TreeNode

        If nodes.Length = 0 Then
            empNode = New TreeNode()  {.Name = empNodeId, .Text = EmpName}
            depNode.Nodes.Add(empNode)
        Else
            empNode = nodes(0)
        End If

    Next
vb.net datagridview treeview
1个回答
0
投票

你从一个数据化的树中填充了数据。通过BindingSource将网格绑定到同一个表中。当你添加节点时,在节点的Tag中存储一个字符串来决定BindingSource过滤器。

depNode = New TreeNode()  {.Name = depNodeId, .Text = depName, .Tag = $"[depNum] = '{dr("depNum")}'"}

为每一种节点设置不同的过滤器(codepemp)

为treeview的AfterSelect事件添加一个处理程序(https:/docs.microsoft.comen-usdotnetframeworkwinformscontrolshow-toeterminewhich-treeview-node-was-click-windows-forms。),并将BindingSource的Filter属性设置为 e.Node.Tag.ToString()

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