user3620870
user3620870

Reputation: 95

How to check whether the selected tree nodes are of same order?

enter image description here

I am designing a treeview which allows the user to select range of nodes by pressing SHIFT, CTRL + start node and then end node. I requirement is to select the nodes only when the range is under a treenode. (Range should not falls under two parent nodes). If user selects Node2 from two different parents i can check like if(selected_node_1->Parent == selected_node_2->Parent). But if the user selects Node_A and Node_B, how can i check whether the selected treenodes are in same level ?

(Pls note Node_A and Node_B has no parents).

Upvotes: 1

Views: 458

Answers (2)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186803

Try this extension method (C#):

  public static class TreeNodeExtensions {
    public static int Level(this TreeNode value) {
      if (Object.ReferenceEquals(null, value))
        throw new ArgumentNullException("value"); // <- or return 0 

      int result = 0;

      for (TreeNode node = value; node != null; node = node.Parent)
        result += 1;

      return result;
    }
  }

  ... 

  TreeNode node1 = ...
  TreeNode node2 = ...

  if (node1.Level() != node2.Level()) {
    ...
  } 

Upvotes: 1

wesol89
wesol89

Reputation: 33

Doesn't they have parent called root? if not you can check if both has parent == null

Upvotes: 1

Related Questions