Find
中有一个
TreeNodeCollection
方法。它返回与节点的
Name
属性匹配的找到节点的数组。我在表单设计器中设置了一个小测试表单(插入 Form1.Designer.vb):
Private Sub InitializeComponent()
Dim TreeNode1 As TreeNode = New TreeNode("Private")
Dim TreeNode2 As TreeNode = New TreeNode("Public")
Dim TreeNode3 As TreeNode = New TreeNode("Data", New TreeNode() {TreeNode1, TreeNode2})
Dim TreeNode4 As TreeNode = New TreeNode("Pictures")
Dim TreeNode5 As TreeNode = New TreeNode("C:", New TreeNode() {TreeNode3, TreeNode4})
TreeView1 = New TreeView()
TextBox1 = New TextBox()
SuspendLayout()
'
' TreeView1
'
TreeView1.HideSelection = False
TreeView1.Location = New Point(55, 213)
TreeView1.Name = "TreeView1"
TreeNode1.Name = "C:\Data\Private"
TreeNode1.Text = "Private"
TreeNode2.Name = "C:\Data\Public"
TreeNode2.Text = "Public"
TreeNode3.Name = "C:\Data"
TreeNode3.Text = "Data"
TreeNode4.Name = "C:\Pictures"
TreeNode4.Text = "Pictures"
TreeNode5.Name = "C:"
TreeNode5.Text = "C:"
TreeView1.Nodes.AddRange(New TreeNode() {TreeNode5})
TreeView1.Size = New Size(262, 144)
TreeView1.TabIndex = 3
'
' TextBox1
'
TextBox1.Location = New Point(55, 364)
TextBox1.Name = "TextBox1"
TextBox1.Size = New Size(262, 23)
TextBox1.TabIndex = 4
'
' Form1
'
AutoScaleDimensions = New SizeF(7F, 15F)
AutoScaleMode = AutoScaleMode.Font
ClientSize = New Size(800, 450)
Controls.Add(TextBox1)
Controls.Add(TreeView1)
Name = "Form1"
Text = "Form1"
ResumeLayout(False)
PerformLayout()
End Sub
Friend WithEvents TreeView1 As TreeView
Friend WithEvents TextBox1 As TextBox
然后我添加了这个 TextChanged 事件处理程序:
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
Dim nodes As TreeNode() = TreeView1.Nodes.Find(TextBox1.Text, True)
If nodes.Length > 0 Then
Dim selectedNode As TreeNode = nodes(0)
TreeView1.SelectedNode = selectedNode
selectedNode.Expand()
selectedNode.EnsureVisible()
End If
End Sub
现在,当我输入路径时,所选节点会不断更新。请注意,节点的名称是到目前为止的整个路径,而显示的文本只是路径的一部分。