我使用以下内容搜索名为" Archive"的节点。然后将其颜色更改为红色和图像索引。
Dim d As String = "Archive"
For i = 0 To tvProgress.Nodes.Count - 1
If tvProgress.Nodes(i).Text = d Then
tvProgress.Nodes(i).ForeColor = Color.Red
tvProgress.Nodes(i).ImageIndex = 1
End If
Next
从下图中可以看到节点"存档"下面有一些结构。我也想改变这些的颜色和图像索引。这些不是静态节点名称,如" Archive"所以我不能简单地重复这个过程。
树视图中还有其他节点需要保留为默认的蓝色文件夹,黑色文本
这可能吗?
答案 0 :(得分:2)
您应该能够使用此代码,只需将d
设置为您要搜索的节点,然后将p
设置为您要保留的任何内容。
'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
用于获取TreeView
中每个节点的过程称为递归过程,这基本上意味着GetRecursive()
将调用自身,直到它通过您的每个节点TreeView
。多亏了这一点,无论深度如何,此代码都将通过任何TreeView
。
这是我用来测试此代码的TreeView
,在代码运行之前:
在运行代码后运行:
我希望这有帮助,任何问题,我会尽力帮助。
如果您只想格式化“存档”下的所有节点,请使用此略微修改的代码:
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