Link to home
Start Free TrialLog in
Avatar of tahir_666
tahir_666

asked on

C# TreeView Control - Find And Select

I have a tag value as string in my program....I want to search that Tag value in Tree control and want to select/expand the node with that Tag value. C# please!!!
Avatar of Jase-Coder
Jase-Coder

ok do

 TreeNodeCollection Nodes = TreeView.Nodes;

 TreeNode Node = Nodes.Find("Node", true);

  Node.Collapse();
Avatar of tahir_666

ASKER

Code seems to have error....but I tried this

            TreeNodeCollection Nodes = tvewNetworkSource.Nodes;

            TreeNode[] Node = Nodes.Find(SectionID, true);

            Node[0].Collapse();

....and No work.
SectionID is string having Tag value.
you would need to search recursively in each node's child
use this function

public TreeNode SearchTree(TreeNodeCollection nodes, string searchtext)
{
      foreach(TreeNode node in nodes)
      {
            if(node.Tag as string  == searchtext)
            {
                  return node;
            }
            SearchTree(node.Nodes, searchtext);
      }            
}

and call it like
TreeNode tn = SearchTree( MyTreeView.Nodes, MySearchString);
//do whatever with tn
I really appriciate ur effort dude...but I have searched the desired node using following code:

            TreeNode[] n = this.tvewNetworkSource.Nodes.Find(SectionID,false) ;

            if (n.Length >0 )
            {
               //Problem
              tvewNetworkSource.SelectedNode = tvewNetworkSource.Nodes[0];
            }

Now Im haveing problem in selecting the searched node. n in this case.
TreeNodeCollection.Find seems to be new thing in .Net 2.0, the code above works for earlier version too :D
2.0 documentation says that 'Find' return treenodes whose 'Name' property matches the specified key, while you need to match tags. one more :D
Shit......UR rite :o)
try Node[0].Expand(); rather than Node[0].Collapse();
So Can I have Code for Search and Selection for a Tag? :-P
ASKER CERTIFIED SOLUTION
Avatar of RoninThe
RoninThe

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Accepted :o)
solution was working only at root level
please use this one

private TreeNode SearchTree(TreeNodeCollection nodes, string searchtext)
        {
            TreeNode n_found_node = null;
            bool b_node_found = false;
            foreach (TreeNode node in nodes)
            {
                if (node.Tag.ToString() as string == searchtext)
                {
                    b_node_found = true;
                    n_found_node = node;
                }
                if (!b_node_found)
                {
                    n_found_node = SearchTree(node.Nodes, searchtext);
                }
            }
            return n_found_node;
        }