2015-04-22 122 views
0

请问有谁知道如何在单击按钮的特定深度搜索多个treeview节点的文本?树形视图节点安排​​如下:如何在特定深度搜索多个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

所有帮助将不胜感激。谢谢。

+0

@TheBlueDog非常感谢您的好评。我期待着你的明智建议。 – Iki

回答

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 
+0

@JSevens - 感谢您的建议。不幸的是,我仍然有这个问题的问题,因为我仍然无法做到我之前解释过的。我是vb.net的新手。 – Iki

+0

@Iki我已经更新了示例,并提供了使用建议... – JStevens

+0

非常感谢您的建议。除了你的第一个建议,你的第二个代码已经为我工作。 – Iki