1

Maybe I couldn't explain well, but this should explain: I have a int field called getParentNode(TreeNode) to get how many parent it has (e.g if there is 2 nodes below node, count will be 2) And I have a List field called getParentNames(TreeNode) that returns all of the parent's names.

getParentCount:

int getParentCount(TreeNode node)
{
    int count = 1;
    while (node.Parent != null)
    {
        count++;
        node = node.Parent;
    }
    return count;
}

getParentsNames:

List<string> getParentNames(TreeNode node)
{
    List<string> list = new List<string>();
    for (int i = 0; i < getParentCount(node); i++)
    {
        //i = 1 : list.Add(node.Parent.Text);
        //i = 2 : list.Add(node.Parent.Parent.Text);
        //i = 3 ...
    }
    return list;
}

Do I need to check if (i == 0) (I don't want to write manually because number can be anything) or something? Regards.

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
Talha Talip Açıkgöz
  • 1,821
  • 4
  • 15
  • 28

3 Answers3

1

why don't you use the node.FullPath counting the TreeView.PathSeparator char? Something like

char ps = Convert.ToChar( TreeView1.PathSeparator);
int nCount = selectedNode.FullPath.Split(ps).Length;
Paolo Ursini
  • 270
  • 1
  • 2
  • 9
1

You can use either of these options:

  • Split FullPath of node by PathSeparator of tree
  • Ancestors and AncestorsAndSelf sxtension methods


Split FullPath of node by PathSeparator of tree

You can use FullPath property of the TreeNode and split the result using PathSeparator property of TreeView. For example:

private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
    var ancestorsAndSelf = e.Node.FullPath.Split(treeView1.PathSeparator.ToCharArray());
}

Ancestors and AncestorsAndSelf sxtension methods

Also you can get all ancestors of a TreeNode. You can simply use a while loop to go up using node.Parent while the parent is not null. I prefer to encapsulate this logic in an extension method and make it more reusable for future. You can create an extension method to return all parent nodes (ancestors) of a node:

using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
public static class TreeViewExtensions
{
    public static List<TreeNode> Ancestors(this TreeNode node)
    {
        return AncestorsInternal(node).Reverse().ToList();
    }
    public static List<TreeNode> AncestorsAndSelf(this TreeNode node)
    {
        return AncestorsInternal(node, true).Reverse().ToList();
    }
    private static IEnumerable<TreeNode> AncestorsInternal(TreeNode node, bool self=false)
    {
        if (self)
            yield return node;
        while (node.Parent != null)
        {
            node = node.Parent;
            yield return node;
        }
    }
}

Usage:

List<TreeNode> ancestors = treeView1.SelectedNode.Ancestors();

You can get text or any other property from ancestors:

List<string> ancestors = treeView1.SelectedNode.Ancestors().Select(x=>x.Text).ToList(); 

Note

JFYI you can use an extension method approach to get all child nodes too. Here I've shared an extension method to to so: Descendants Extension Method.

Community
  • 1
  • 1
Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
  • Oh, that looks pretty good. But i do not understand that exception method can be called from treeView1.SelectedNode . – Talha Talip Açıkgöz Oct 09 '16 at 16:34
  • Thanks for the feedback :) - **Extension Methods** in fact extend a type and add new method to it. In above scenario after adding `TreeViewExtensions` to your program (in a namespace) and using that namespace in a form, `treeView1.SelectedNode` will have an `Ancestors()` method which you can use to get all ancestors of a node. I used the same technique to also get all [descendants](http://stackoverflow.com/a/32360956/3110834) of a node. – Reza Aghaei Oct 09 '16 at 16:54
  • It's really a clean and elegant mechanism to add new reusable functionality to types. (For example most linq methods are extension methods which doesn't actually exists in `List`, but after using `System.Linq` they will be added to some types like `List`. – Reza Aghaei Oct 09 '16 at 16:55
  • Thanks for the explanation :) – Talha Talip Açıkgöz Oct 09 '16 at 16:59
0

Anyways, I noticed that I need to use while loop:

List<string> getParentNames(TreeNode node)
    {
        List<string> list = new List<string>();
        int count = getParentCount(node);
        int index = 0;
        TreeNode parent = node;
        while (index < count)
        {
            if (parent != null)
            {
                index++;
                list.Add(parent.Text);
                parent = parent.Parent;
            }
        }
        return list;
    }
Talha Talip Açıkgöz
  • 1,821
  • 4
  • 15
  • 28
  • 1
    [`Ancestors`](http://stackoverflow.com/a/39805732/3110834) extension method is much better. It returns a `List` which you can simply use to get a count or any property of nodes like `Text` from the list. – Reza Aghaei Oct 02 '16 at 06:17
  • 1
    Probably you have no idea about what an extension method is or how to use it. [Extension methods](https://msdn.microsoft.com/en-us//library/bb383977.aspx) enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. – Reza Aghaei Oct 02 '16 at 06:20