2

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];
Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
  • Use keys when creating nodes. If they are unique, then you will be able to select by key. – Alex Dec 11 '15 at 16:57
  • The Tag property is useless, use the TreeNode.Name property instead. No need to recurse to find it back, it lights up the ContainsKey() method and the indexer, just as you planned. Poor naming btw, they should have called it TreeNode.Key instead. – Hans Passant Dec 11 '15 at 17:01

1 Answers1

4

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.

Community
  • 1
  • 1
Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398