让代码吼叫;逻辑中出现错误,不显示错误消息。
我正在尝试使用treeview1
更改事件来过滤textbox1.text
控件。
预期结果是在treeview1
中保留仅与textbox1.text
类似的节点(SQL中的%text%)
我在C#
找到了很多解决方案的结果,但无法在 VB.NET
中找到答案。
Referencing this answer,并将代码转换为VB.NET,几乎没有变化仍然无效:
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
Try
Dim FilterText As String = TextBox1.Text
TreeView1.BeginUpdate()
If (FilterText IsNot String.Empty) Then
For Each Node As TreeNode In TreeView1.Nodes
If Not Node.Text.Contains(FilterText) Then
Node.Remove()
TreeView1.Refresh()
End If
Next
Else
Exit Sub
End If
TreeView1.EndUpdate()
Catch ex As Exception
End Try
End Sub
答案 0 :(得分:0)
以下是代码我只为所选节点着色。你可以根据需要改变
Public Class Form1
Dim matchedNodes As List(Of TreeNode) = New List(Of TreeNode)
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
matchedNodes.Clear()
If Not String.IsNullOrEmpty(TextBox1.Text) Then
TreeView1.BeginUpdate()
For Each node As TreeNode In TreeView1.Nodes
FindRecursive(node)
Next
TreeView1.EndUpdate()
End If
For Each match In matchedNodes
match.BackColor = Color.Yellow
Next
TreeView1.Refresh()
End Sub
Private Sub FindRecursive(treeNode As TreeNode)
treeNode.BackColor = Color.White
If treeNode.Text.Contains(TextBox1.Text) Then
matchedNodes.Add(treeNode)
End If
For Each node As TreeNode In treeNode.Nodes
If node.Text.Contains(TextBox1.Text) Then
matchedNodes.Add(node)
End If
FindRecursive(node)
Next
End Sub
End Class
答案 1 :(得分:0)
经过几个帖子的阅读;将过滤器应用于treeview非常简单。 即使我最初想要隐藏其他不在过滤器中的节点,但这段代码是实用的并且可以完成工作。
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
Dim TxtToFilter As String = TextBox1.Text
Dim NodeItem As TreeNode
For Each NodeItem In TreeView1.Nodes
If NodeItem.Text.ToLower.Contains(TxtToFilter.ToLower) And TxtToFilter IsNot String.Empty Then
NodeItem.EnsureVisible()
NodeItem.BackColor = Color.Yellow
Else
NodeItem.BackColor = TreeView1.BackColor
End If
Next
End Sub
注意:强> 当所有节点都是我的app逻辑中的root / parents时,此代码有效。 没有测试子节点。