Home > Back-end >  How to iterate through TreeView elements?
How to iterate through TreeView elements?

Time:12-01

I've been looking pretty much everywhere on here for an answer but could not find a working one..

I come from a VBA heavy background so I understand the syntax very well, but I still don't understand how WPF Application works in NET 6.0, lol.

The situation is as follows:

I have one TreeView element in my Application Window, it has two parents and one child each.

My VBA brain logic would say something like

x = 0
Do While x < TreeViewObject.Items(x).Count ' This would be the iteration for finding out parents
y = 0

Do While y < TreeViewObject.Items(x).Children.Count ' This would be the iteration for finding out how many children the parents have.

Msgbox(TreeViewObject.Items(x).Children(y)) ' prints out the children's values

y = y   1
Loop

x = x   1
Loop

..would work, but the logic here is MUCH worse than I expected, how can I iterate through a TreeView element?

CodePudding user response:

This demonstrates using recursion to walk a Treeview

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    IterateTV(TreeView1.Nodes(0))
End Sub

Private Sub IterateTV(nd As TreeNode)
    Debug.Write("' ")
    Debug.WriteLine(nd.Text)
    For Each tnd As TreeNode In nd.Nodes
        IterateTV(tnd)
    Next
End Sub
'TreeView1
' root
'   A
'   B
'       B sub 1
'       B sub 2
'           B sub 2 sub a
'       B sub 3
'   C

CodePudding user response:

Disregarding my older post, this implementation is wholly superior:

        For Each VarParent In CategoryList.Items
            MsgBox(VarParent.ToString)

            For Each VarChild In VarParent.Items
                MsgBox(VarChild.ToString)
            Next

        Next

This method will loop through each parent, then each children it has, with logic similar to what you would find in VBA with 0 extra complications.

Old code:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    IterateTV(CategoryList)
End Sub

Private Sub IterateTV(nd)
    For Each tnd In nd.Items
        IterateTV(tnd)
        MsgBox(tnd.ToString)
    Next
End Sub
  • Related