If I have a TreeView (myTreeview),how can I obtain a list of all parent nodes (parent, parents of parents ect.) of selected node?
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.
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.
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.
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)
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With