vb.net 如何在 Treeview 控件的父节点中搜索子节点的文本
How to search the text of child nodes within a parent node in a Treeview control in vb.net
我有一个在 运行 时间内生成的 Treeview 控件结构,它通过单击专用按钮将带有从文本框获取的文本的子节点添加到父节点。
现在,随着更多的子节点被添加到特定的父节点,我想通过单击按钮来搜索该父节点中先前添加的子节点的名称(文本),以防止用户添加具有相同名称的重复节点。
如果发生这种情况,用户应该会收到一条消息,表明已将具有相同名称的子节点添加到该特定父节点。我已经编写了一个代码来解决彼此相邻的子节点的这个问题,即如果用户将一个名为“Frank”的子节点添加到一个名为“Family”的父节点,然后尝试在 wards 之后立即再次添加“Frank”, he/she 会得到“Frank”已经添加到“Family”父节点的消息。
我的问题是,如果用户添加“Frank”,然后添加“Shelly”,然后添加“Mark”,然后再次添加“Frank”,he/she 将不会收到消息。解决这个问题的最佳方法是什么?
我想你想获取刚刚输入的子节点的父节点,从该父节点检索所有子节点,然后遍历子节点以查看是否有任何节点具有相同的名称.
它可能是这样的:
Dim currentNode As TreeNode = TreeView1.SelectedNode ' The node we just entered
Dim targetName As String = TextBox1.Text.trim.toLower ' The string we're searching against - we trim and set to lower for comparison purposes
Dim parentNode = currentNode.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
If tempNode.Text.trim.toLower = targetName Then WeHaveDuplicate = True ' Test that we have the same name but not referring to the same node
Next
If WeHaveDuplicate= True Then
' Send message to user
' Do not add new node to treeview
Else
' Add new node to treeview
End If;
更新:我修改了此代码以使用文本框文本而不是所选节点的当前值来确定是否存在匹配项。
我有一个在 运行 时间内生成的 Treeview 控件结构,它通过单击专用按钮将带有从文本框获取的文本的子节点添加到父节点。
现在,随着更多的子节点被添加到特定的父节点,我想通过单击按钮来搜索该父节点中先前添加的子节点的名称(文本),以防止用户添加具有相同名称的重复节点。
如果发生这种情况,用户应该会收到一条消息,表明已将具有相同名称的子节点添加到该特定父节点。我已经编写了一个代码来解决彼此相邻的子节点的这个问题,即如果用户将一个名为“Frank”的子节点添加到一个名为“Family”的父节点,然后尝试在 wards 之后立即再次添加“Frank”, he/she 会得到“Frank”已经添加到“Family”父节点的消息。
我的问题是,如果用户添加“Frank”,然后添加“Shelly”,然后添加“Mark”,然后再次添加“Frank”,he/she 将不会收到消息。解决这个问题的最佳方法是什么?
我想你想获取刚刚输入的子节点的父节点,从该父节点检索所有子节点,然后遍历子节点以查看是否有任何节点具有相同的名称.
它可能是这样的:
Dim currentNode As TreeNode = TreeView1.SelectedNode ' The node we just entered
Dim targetName As String = TextBox1.Text.trim.toLower ' The string we're searching against - we trim and set to lower for comparison purposes
Dim parentNode = currentNode.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
If tempNode.Text.trim.toLower = targetName Then WeHaveDuplicate = True ' Test that we have the same name but not referring to the same node
Next
If WeHaveDuplicate= True Then
' Send message to user
' Do not add new node to treeview
Else
' Add new node to treeview
End If;
更新:我修改了此代码以使用文本框文本而不是所选节点的当前值来确定是否存在匹配项。