You should be able to use this code, just set d
to the node you want to search for, and p
to anything you want to preserve.
'This stores every node in the TreeView
Dim allNodes As New List(Of TreeNode)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'the node you want to search for
Dim d As String = "Archive"
'the node you want to preserve
Dim p As String = "Preserve"
CallRecursive(TreeView1)
For Each n As TreeNode In allNodes
If n.Text = d Then
n.ForeColor = Color.Red
n.ImageIndex = 1
ElseIf Not n.Text = p Then
Dim path As String = n.FullPath
Dim l As List(Of String) = path.Split("\").ToList()
If l.Contains(d) Then
If l.IndexOf(n.Text) > l.IndexOf(d) Then
n.ForeColor = Color.Red
n.ImageIndex = 1
End If
End If
End If
Next
End Sub
Private Sub GetRecursive(ByVal n As TreeNode)
allNodes.Add(n)
Dim aNode As TreeNode
For Each aNode In n.Nodes
GetRecursive(aNode)
Next
End Sub
Private Sub CallRecursive(ByVal aTreeView As Windows.Forms.TreeView)
allNodes.Clear()
Dim n As TreeNode
For Each n In aTreeView.Nodes
GetRecursive(n)
Next
End Sub
The procedure used to get every node in the TreeView
is called recursive procedure, which basically means that GetRecursive()
will call itself until it has been through every node in your TreeView
. Thanks to this, this code will go through any TreeView
, regardless of depth.
This is the TreeView
I used to test this code, before the code is run:
And after the code is run:
I hope this helps, any problems and I will try and help.
Edit:
If you just want to format all nodes under "Archive", use this slightly modified code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'the node you want to search for
Dim d As String = "Archive"
CallRecursive(TreeView1)
For Each n As TreeNode In allNodes
If n.Text = d Then
n.ForeColor = Color.Red
n.ImageIndex = 1
Else
Dim path As String = n.FullPath
Dim l As List(Of String) = path.Split("\").ToList()
If l.Contains(d) Then
If l.IndexOf(n.Text) > l.IndexOf(d) Then
n.ForeColor = Color.Red
n.ImageIndex = 1
End If
End If
End If
Next
End Sub
Private Sub GetRecursive(ByVal n As TreeNode)
allNodes.Add(n)
Dim aNode As TreeNode
For Each aNode In n.Nodes
GetRecursive(aNode)
Next
End Sub
Private Sub CallRecursive(ByVal aTreeView As Windows.Forms.TreeView)
allNodes.Clear()
Dim n As TreeNode
For Each n In aTreeView.Nodes
GetRecursive(n)
Next
End Sub