How to select a Node by Tag in Windows Forms TreeView

后端 未结 1 1863
说谎
说谎 2020-12-11 11:28

I\'m trying to select a node by tag. I\'ve searched what I can, but still with no luck. I used this to assign a tag to each node in my treeview

         


        
相关标签:
1条回答
  • 2020-12-11 12:17

    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.

    0 讨论(0)
提交回复
热议问题