Find By Tag
Finding by Tag
is useful specially when the Tag
contains a complex object or you want to find based on a non-string key.
To be able to search on child nodes, you can take a look at the answer here and use Descendants
extension method to find all nodes including child nodes. Then you can find the node by Tag
. For example if the Tag
contains a Product
and you want to find the product based on its Id
, you can use such code:
var result = tree.Descendants().Where(x=>((x.Tag as Product) != null) &&
(x.Tag as Product).Id = someId).FirstOrDefault();
Or for a simple string search key:
var result = tree.Descendants().Where(x=>(x.Tag as string) == searchkey).FirstOrDefault();
if(result!=null)
tree.SelectedNode = result;
If you want to search just between root nodes, use:
var result = tree.Nodes.Cast<TreeNode>().Where(... the rest is like above.
Find By Name
You can use Find
method of Nodes
collection to find a node based on its Name
(not the Text). Using Find
method is useful when you want to find a node based on a string key. To do so, you should set the Name
of node when you create the node.
var result = tree.Nodes.Find(searchKey , true).FirstOrDefault();
if(result !=null)
tree.SelectedNode = result;
If you want to search just between root nodes, use:
var result = tree.Nodes.Find(searchKey , false).FirstOrDefault();
Note
As a conclusion you can use the Tag
property to store a complex object in Tag
and unbox it when you need. For string search keys, it's better to use Name
property as said in the comments.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…