Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Winform Treeview find node by tag

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);

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!

like image 444
user1548103 Avatar asked Oct 07 '13 13:10

user1548103


People also ask

How do you find a node in TreeView?

TreeView enables you to search for the nodes matching the specified string. To search for a node in TreeView, you can use Search or SearchAll method of C1TreeView class. The Search method takes string as a value, searches for the nodes using depth-first search and returns the node containing the searched string.

How do I know if TreeView node is selected?

Solution 1Use TreeView. SelectedNode[^] property, which get or set selected node for currently selected Treeview. If no TreeNode is currently selected, the SelectedNode property is a null reference (Nothing in Visual Basic).

What is TreeView node?

A tree view is a component to navigate hierarchical lists. It is made up of one or more top level nodes. A node may have children or it may be an end node. Nodes with children can be expanded or collapsed - when expanded its child nodes are visible.


1 Answers

Try this:

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

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.

UPDATE

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;
}
like image 153
King King Avatar answered Sep 21 '22 19:09

King King