如何计算和获取vb net中最后一级树视图节点的子项?

时间:2015-10-01 07:30:54

标签: vb.net treeview

如果只有如下图所示的根元素,我想计算并获取treeview的子名称。我在Item1的位置。

 Item1
    |_____SubItem1
                 |___A
                 |___B

结果应为Count:2,项目:A, B

3 个答案:

答案 0 :(得分:2)

此解决方案依赖于您的TreeView深度不会更改。如果你将有更深层次,你需要让它变得更聪明。

       For Each nd As TreeNode In TestTreeView.Nodes
            If nd.Nodes.Count > 0 Then 'it has children, lets look at them
                For Each ndChild As TreeNode In nd.Nodes
                    If ndChild.Nodes.Count > 0 Then 'it has children, lets look at them
                        Dim outputText As String = String.Concat(ndChild.Text, " ",
                                                                 ndChild.Nodes.Count)
                        For Each ndSubChild As TreeNode In ndChild.Nodes
                            outputText = String.Concat(outputText, " ", ndSubChild.Text)
                        Next
                        Debug.Print(outputText)
                    End If
                Next
            End If
        Next

答案 1 :(得分:1)

也是一种可能的解决方案,使用LINQ:

Dim result = (From node as TreeNode in TreeView1.TopNode.Nodes
              Select New With {
                .Count = node.Nodes.Count,
                .Items = String.Join(",", node.Nodes.Cast(Of TreeNode).AsEnumerable().Select(Function(childNode) childNode.Name).ToArray())
              })

答案 2 :(得分:0)

**'Its work for me. Thanks** 




 Dim outputText As String


        For Each nd As TreeNode In TreeView1.Nodes
            If nd.Nodes.Count > 0 Then 'it has children, lets look at them
                For Each ndChild As TreeNode In nd.Nodes
                    outputText = String.Concat(ndChild.Text, " - (Total : ", ndChild.Nodes.Count, ")")
                    TextBox4.Text += outputText & vbNewLine

                    If ndChild.Nodes.Count > 0 Then 'it has children, lets look at them
                        For Each ndSubChild As TreeNode In ndChild.Nodes
                            outputText = String.Concat(vbTab, " - ", ndSubChild.Text)
                            TextBox4.Text += outputText & vbNewLine

                            If ndSubChild.Nodes.Count > 0 Then 'it has children, lets look at them
                                For Each ndSubSubChild As TreeNode In ndSubChild.Nodes
                                    outputText = String.Concat(vbTab, vbTab, " - ", ndSubSubChild.Text)
                                    TextBox4.Text += outputText & vbNewLine
                                Next
                            End If
                        Next
                    End If
                Next
            End If
        Next