[英]C# - Find a specific node or subnode of a treeview control
I have a problem with the TreeView control in WinForm.我在 WinForm 中的 TreeView 控件有问题。 The thing is, I need to automate the process of inserting nodes by using a while loop and using the node previously inserted in the control as the parent node search criterion.
问题是,我需要通过使用 while 循环并使用先前插入控件中的节点作为父节点搜索标准来自动化插入节点的过程。
Here my problem arises, when I look for the node in the control I use this code:这里出现了我的问题,当我在控件中查找节点时,我使用以下代码:
foreach (TreeNode singleNode in Repository_TreeView.Nodes)
{
if (singleNode.Text.Contains(specificPTN) == true)
{
Repository_TreeView.SelectedNode = singleNode;
}
In this way, however, I only get the nodes in the highest level of the hierarchy.但是,通过这种方式,我只能获得层次结构最高级别的节点。 So, for example:
因此,例如:
/--------------------------------------------------\
| + rootnode1 |
| | +---> childnode1 |
| | +---> grandchildnode1 |
| | | |
| | +---> grandchildnode1 |
| | |
| + rootnode2 |
| +---> childnode2 |
| +---> grandchildnode2 |
| | |
| +---> grandchildnode2 |
| |
| |
\--------------------------------------------------/
In this case my code would only get the node 'rootnode1' and 'rootnode2', when I need to get all the other subnodes instead.在这种情况下,当我需要获取所有其他子节点时,我的代码只会获取节点“rootnode1”和“rootnode2”。
I also tried using this lambda expression to look up the node by name:我还尝试使用此 lambda 表达式按名称查找节点:
TreeNode[] parentNodes = Repository_TreeView.Nodes
.Cast<TreeNode>()
.Where(r => r.Text == specificPTN)
.ToArray();
The result, however, is always the same, 'rootnode1' and 'rootnode2' are always found.然而,结果总是相同的,总是能找到 'rootnode1' 和 'rootnode2'。
I hope someone can help me find a way to get all the nodes and subnodes out of control.我希望有人能帮我找到一种让所有节点和子节点失控的方法。 Thanks and sorry for the long explanation.
感谢并抱歉这么长的解释。
By iterating over TreeView->Nodes , you are getting only top level Nodes.通过迭代 TreeView->Nodes ,您只能获得顶级节点。 TreeView->Nodes(of type TreeNodeCollection) has a Find(string, boolean) method that you can use to search for a node with specific text.
TreeView->Nodes(属于 TreeNodeCollection 类型)有一个 Find(string, boolean) 方法,可用于搜索具有特定文本的节点。 You can call this method like
你可以像这样调用这个方法
Repository_TreeView.Nodes.Find(specificPTN, true)
to get all the matching nodes.获取所有匹配的节点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.