Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all parents (up to root) nodes for selected in TreeView control?

If I have a TreeView (myTreeview),how can I obtain a list of all parent nodes (parent, parents of parents ect.) of selected node?

like image 738
DevUser Avatar asked Nov 14 '11 11:11

DevUser


People also ask

How many root nodes can a TreeView control have?

A typical tree structure has only one root node; however, you can add multiple root nodes to the TreeView control. The Nodes property can also be used to manage the root nodes in the tree programmatically.

How do I know if TreeView node is selected?

SelectedNode; if ( tn == null ) Console. WriteLine("No tree node selected."); else Console. WriteLine("Selected tree node {0}.", tn.Name ); You can compare the returned TreeNode reference to the TreeNode you're looking for, and so check if it's currently selected.

Which of the following property is used to set the height between nodes of TreeView?

The ItemHeight property is used to set the height of each tree node in control. The Scrollable property is used in the tree-view to display the scroll bar by setting the value in control.


2 Answers

I'd recomended you to create a set of your own tree helpers, for example, next one is for your problem:

    public static class TreeHelpers
    {
        public static IEnumerable<TItem> GetAncestors<TItem>(TItem item, Func<TItem, TItem> getParentFunc)
        {
            if (getParentFunc == null)
            {
                throw new ArgumentNullException("getParentFunc");
            }
            if (ReferenceEquals(item, null)) yield break;
            for (TItem curItem = getParentFunc(item); !ReferenceEquals(curItem, null); curItem = getParentFunc(curItem))
            {
                yield return curItem;
            }
        }

        //TODO: Add other methods, for example for 'prefix' children recurence enumeration
    }

And example of usage (in your context):

        IList<TreeNode> ancestorList = TreeHelpers.GetAncestors(node, x => x.Parent).ToList();

Why is this better than using list<>.Add()? - because we can use lazy LINQ functions, such as .FirstOrDefault(x => ...)

P.S. to include 'current' item into result enumerable, use TItem curItem = item, instead of TItem curItem = getParentFunc(item)

like image 78
Alexander Mavrinsky Avatar answered Sep 23 '22 02:09

Alexander Mavrinsky


If you want the actual objects, use the TreeNode.Parent property recursively until you reach the root. Something like:

private void GetPathToRoot(TreeNode node, List<TreeNode> path)
{
    if(node == null) return; // previous node was the root.
    else
    {
        path.add(node);
        GetPathToRoot(node.Parent, path);
    }
}
like image 39
Tudor Avatar answered Sep 19 '22 02:09

Tudor