Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

treeview how to expand a fullpath

Tags:

c#

I need to expand my treeview based on a fullpath in c#

My tree view has 2 nodes which are collapsed and I want to expand Node A to number 3 so I have the fullpath of node A\1\2\3.

How can I step through and open each node based of the fullpath? Also the length of the fullpath may change, so i may need to open node be to level 6. So it needs to be done based on the fullpath. Any help would be great.

Node A
       1
         2
          3
Node B
1
 2
  3
   4 5 6

This is what I've tried:

TreeNode [] n= treeView1.Nodes.Find(search, true);

if (n.Length > 0)
  found = true;
treeView1.Nodes[t].Collapse();
foreach (TreeNode p in n) {
  string[] a = p.FullPath.Split('\\');
  foreach (string b in a) {
    treeView1.SelectedNode = treeView1.Nodes[b];
    treeView1.SelectedNode.Expand();
like image 792
Kevin Babb Avatar asked Jan 29 '26 11:01

Kevin Babb


1 Answers

I'm sorry for not commenting on above answer given by S3ddi9 which is CORRECT. I'm only adding something.

So the answer given by S3ddi9

    ...
    string path = @"A\1\2\";

    var path_list = path.Split('\\').ToList();
    foreach (TreeNode node in treeView1.Nodes)
        if (node.Text == path_list[0])
            ExpandMyLitleBoys(node, path_list);
}

private void ExpandMyLitleBoys(TreeNode node, List<string> path)
{
    path.RemoveAt(0);

    node.Expand();

    if (path.Count == 0)
        return;

    foreach (TreeNode mynode in node.Nodes)
        if (mynode.Text == path[0])
          {  
             ExpandMyLitleBoys(mynode, path); //recursive call
             break;  //this was missing in earlier answer
          } 

}

Does work, BUT you must add a BREAK (I marked it), because if the for loop doesn't finish, return; won't return you to your main function and it will throw you an exception because path[0] is null.

like image 59
Antun Matic Avatar answered Jan 31 '26 00:01

Antun Matic