FurtiveFelon
FurtiveFelon

Reputation: 15186

how to go from TreeNode.FullPath data and get the actual treenode?

I would like to store some data from TreeNode.FullPath and then later i would like to re-expand everything up to that point. Is there a simple way of doing it?

Thanks a lot!

Upvotes: 5

Views: 6984

Answers (3)

McMillan Cheng
McMillan Cheng

Reputation: 380

You are able to locate the specific treenode using comparison of fullpath and TreeNode.Text.

TreeNode currentNode;

string fullpath="a0\b0\c0";   // store treenode fullpath for example

string[] tt1 = null;
tt1 = fullpath.Split('\\');
for (int i = 0; i < tt1.Count(); i++)
{
    if (i == 0)
    {
            foreach (TreeNode tn in TreeView1.Nodes)
            {
                if (tn.Text == tt1[i])
                {
                    currentNode = tn;
                }
            }
    }
    else
    {
            foreach (TreeNode tn in currentNode.Nodes)
            {
                if (tn.Text == tt1[i])
                {
                    currentNode = tn;
                }
            }
        }
}
TreeView1.SelectedNode = currentNode;

Upvotes: 0

Vincent Dewisme
Vincent Dewisme

Reputation: 31

You can write it as an extension method to the TreeNodeCollection:

using System;
using System.Linq;
using System.Windows.Forms;

namespace Extensions.TreeViewCollection
{
    public static class TreeNodeCollectionUtils
    {
        public static TreeNode FindTreeNodeByFullPath(this TreeNodeCollection collection, string fullPath, StringComparison comparison = StringComparison.InvariantCultureIgnoreCase)
        {
            var foundNode = collection.Cast<TreeNode>().FirstOrDefault(tn => string.Equals(tn.FullPath, fullPath, comparison));
            if (null == foundNode)
            {
                foreach (var childNode in collection.Cast<TreeNode>())
                {
                    var foundChildNode = FindTreeNodeByFullPath(childNode.Nodes, fullPath, comparison);
                    if (null != foundChildNode)
                    {
                        return foundChildNode;
                    }
                }
            }

            return foundNode;
        }
    }
}

Upvotes: 3

newenglander
newenglander

Reputation: 21

I had a similar problem (but I just wanted to find the treenode again) and found this:

http://c-sharpe.blogspot.com/2010/01/get-treenode-from-full-path.html

i know it only answers part of your problem, but better than no replies at all ;)

Upvotes: 2

Related Questions