Friday, January 8, 2010

Get TreeNode from Full Path in Winform

This is a recursive method that finds a TreeNode in a .NET TreeView control from its full path.

public TreeNode GetNodeFromPath(TreeNode node, string path)
        {
        TreeNode foundNode = null;
        foreach (TreeNode tn in node.Nodes)
        {
            if (tn.FullPath == path)
            {                 
                return tn;
            }
            else if (tn.Nodes.Count > 0)
            {
                foundNode = GetNodeFromPath(tn, path);
            }
            if (foundNode != null)
                return foundNode;
        }
        return null;
        }


7 comments:

  1. Too bad there's no built-in function from Microsoft, could have been a bit quicker than a recursive tree search....

    ReplyDelete
  2. If there are two or more elements with the same name at the same level in the tree, this will return the first of the elements....

    ReplyDelete
  3. I guess that's a limitation. Any suggestions are welcome.

    ReplyDelete
  4. Have a look at this one:
    http://pradeep1210.spaces.live.com/Blog/cns!2E84C99518D46BB4!258.entry

    ReplyDelete
  5. //I guess this is what you are searching for:

    // search recursively
    private TreeNode FindNode(TreeNodeCollection tncoll, String strText)
    {
    TreeNode tnFound;
    foreach (TreeNode tnCurr in tncoll)
    {
    if (tnCurr.FullPath == strText)
    {
    return tnCurr;
    }
    tnFound = FindNode(tnCurr.Nodes, strText);
    if (tnFound != null)
    {
    return tnFound;
    }
    }
    return null;
    }

    // call it with
    private void Button1_Click(object sender, EventArgs e)
    {
    tv_categories.SelectedNode = FindNode(tv_categories.Nodes, @"Full\Path");
    }

    ReplyDelete