How to get all parents (up to root) nodes for selected in TreeView 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);
}
}