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!
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.
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).
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.
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
.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With