Winform Treeview通过标签查找节点 [英] Winform Treeview find node by tag

查看:86
本文介绍了Winform Treeview通过标签查找节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个树状视图,其中显示成员可能有重复项,而标签则没有.示例:

I have a treeview where the display member could possibly have duplicates, and the tag would not. Example:

TreeNode node = new TreeNode(itemName);
node.Tag = itemID; //unique ID for the item
treeView1.Nodes.Add(node);

因此,当我搜索时,我知道我可以使用

So, when searching, I know I can search by the itemName by using

treeView1.Nodes.Find(itemName, true);

但是如何通过标签进行搜索?这里没有treeView1.Nodes.的定义,所以对我来说没有linq:(

But how could I go about searching via the tag? There's no definition for treeView1.Nodes.Where, so no linq for me :(

关于如何通过标签进行搜索的任何建议?:)谢谢!

Any suggestions on how to search by the tag? :) Thank you!

推荐答案

尝试一下:

var result = treeView1.Nodes.OfType<TreeNode>()
                            .FirstOrDefault(node=>node.Tag.Equals(itemID));

注意:由于您说 itemID 是唯一的,因此可以使用 FirstOrDefault 搜索唯一项.如果找不到,则 result 将为 null .

NOTE: Because you said your itemID is unique, so you can use FirstOrDefault to search for the unique item. If it's not found the result will be null.

要搜索所有级别的所有节点,您可以尝试使用某种递归方法,例如:

To search for all the nodes at all levels, you can try using some recursive method, like this:

public TreeNode FromID(string itemId, TreeNode rootNode){
   foreach(TreeNode node in rootNode.Nodes){
     if(node.Tag.Equals(itemId)) return node;
     TreeNode next = FromID(itemId, node);
     if(next != null) return next;
   }
   return null;
}
//Usage    
TreeNode itemNode = null;
foreach(TreeNode node in treeView1.Nodes){
  itemNode = FromID(itemId, node);
  if(itemNode != null) break;
}

这篇关于Winform Treeview通过标签查找节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆