Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
740 views
in Technique[技术] by (71.8m points)

c# - How to select a Node by Tag in Windows Forms TreeView

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

 foreach (DataRow dataRow in databaseFunc.dataTable.Rows)
 {
      TreeNode nodes = new TreeNode();
      nodes.Text = dataRow["LastName"].ToString().Trim() + ", " +
            dataRow["FirstName"].ToString().Trim();
      nodes.Tag = dataRow[0].ToString().Trim();
      treeView.Nodes.Add(nodes);
 }

I know you can select a node using:

 TreeNodeCollection nodeCollect = treeView.Nodes;
 treeView.SelectedNode = nodeCollect[index];
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...