2
votes

I have a tree that looks something like this:

+Parent
       -Child
+Parent
       -Child
       +Parent
              -Child
+Parent
+Parent
       +Parent
              +Parent
                     -Child
                     -Child... etc.

I need to be able to identify all the nodes that are parents, regardless of the level. Basically I need an exampleTree.Nodes.GetAllParents() method.

1
What have you tried? What didn't work? What do you mean identify? Do you mean iterate through and look at each one? Are you asking if there's a way to just "get all parents" ? We need more info to help you. - Tim
Yes, basically I'm asking if there's a way to do something like exampleTree.Nodes.GetParents(); and I haven't really 'tried' anything, I'm researching a way, but so far I've not stumbled upon anything that's really useful. - Schadenfreude
I would update your post to reflect that, as its a little unclear and some people will probably downvote it. - Tim

1 Answers

3
votes

A couple of extension methods that I use:

public static class TreeViewEx {

  public static List<TreeNode> GetParentNodes(this TreeView treeView) {
    List<TreeNode> results = new List<TreeNode>();
    foreach (TreeNode node in treeView.Nodes) {
      results.AddRange(GetNodes(node));
    }
    return results;
  }

  private static List<TreeNode> GetNodes(TreeNode parentNode) {
    List<TreeNode> results = new List<TreeNode>();
    if (parentNode.Nodes.Count > 0) {
      results.Add(parentNode);
      foreach (TreeNode node in parentNode.Nodes) {
        results.AddRange(GetNodes(node));
      }
    }
    return results;
  }

}

Usage would be as such:

List<TreeNode> parents = treeView1.GetParentNodes();