如何在特定深度搜索多个树视图节点

时间:2015-04-22 18:42:09

标签: vb.net treeview

请有人知道如何在点击按钮时搜索特定深度的多个树视图节点的文本吗?树视图节点排列如下:

enter image description here

我想阻止用户将相同标题的重复孙子节点输入到树视图中,即第二次输入“电影2”应该抛出已经输入电影2的消息;如果没有,则添加新的电影标题。

孙子节点标题从文本框输入到树视图中。我正在使用Visual Basic 2010 Express。提前谢谢。

我使用的代码是:

Private Sub Button11_Click(sender As System.Object, e As System.EventArgs) Handles Button11.Click
        

'New movie title has been introduced into the study
        Dim SelectedNode As TreeNode
        SelectedNode = TreeView1.SelectedNode

        'To avoid entering duplicate movies title
        Dim NewMovieName As String = TextBox1.Text.Trim.ToLower ' The content of that node
        Dim parentNode = SelectedNode.Parent ' Get the parent
        Dim childNodes As TreeNodeCollection = parentNode.Nodes ' Get all the children 
        Dim WeHaveDuplicate As Boolean = False ' We use this to flag if a duplicate is found.  Initially set to false.

        For Each tempNode As TreeNode In childNodes
            'Test that we have the same name but not referring to the same node
            If tempNode.Text.Trim.ToLower = NewMovieName And tempNode IsNot parentNode Then WeHaveDuplicate = True
        Next

        If WeHaveDuplicate = True Then
            'Send message to user
            MsgBox(TextBox1.Text & " as a parameter has already been considered.", vbOKOnly)
            Exit Sub
        Else
            parentNode.Nodes.Add(TextBox1.Text)
            TreeView1.ExpandAll()
        End If
        Exit Sub

    End Sub

非常感谢所有帮助。谢谢。

1 个答案:

答案 0 :(得分:1)

这是我经常使用的一小段代码。它将通过它的文本找到一个节点。它还将突出显示和扩展找到的节点。

注意它是递归的,因此它将搜索提供的节点集合(param)的底部。如果此提供的集合是根节点,那么它将搜索整个树。

我通常将唯一的字符串应用于node.tag属性。如果您调整功能以查找它,您可以显示重复的文本,同时仍然有一个唯一的字符串可供查找...

''' <summary>
''' Find and Expand Node in Tree View
''' </summary>
Private Function FindNode(ByVal SearchText As String, ByVal NodesToSearch As TreeNodeCollection, ByVal TreeToSearch As TreeView) As TreeNode
    Dim ReturnNode As TreeNode = Nothing
    Try
        For Each Node As TreeNode In NodesToSearch
            If String.Compare(Node.Text, SearchText, True) = 0 Then
                TreeToSearch.SelectedNode = Node
                Node.Expand()
                ReturnNode = Node
                Exit For
            End If
            If ReturnNode Is Nothing Then ReturnNode = FindNode(SearchText, Node.Nodes, TreeToSearch)
        Next
    Catch ex As Exception
        Throw
    End Try
    Return ReturnNode
End Function
编辑


根据您最近的评论,
您可以尝试使用它......

WeHaveDuplicate = (FindNode("Movie 2", TreeView1.Nodes, TreeView1) Is Nothing)
If WeHaveDuplicate = True Then
  'message user of dupe
Else
  'add movie
End If