2

I want to set the TreeView.selected node by itterating a int List but I can't figure out how to set the childNodes. I have the following code in my custom control:

 private void SetSelectedNode()
    {
        if (MySelectedNodeIndexes == null) return;

        for (int i = 0; i < MySelectedNodeIndexes.Count; i++)
        {
            this.SelectedNode = this.Nodes[MySelectedNodeIndexes[i]];

        }            
    }

This only sets the node but on the first itteration. But the second itteration should set this.SelectedNode.Nodes[first entry in MyselctedNodesIndexes].SelectedNode. and so on.

If MySelectedNodeIndexes contains {2,4,7,1} I want the selected Nodes to be: this.Nodes[2].nodes[4].nodes[7].nodes[1];

I don't know how to do this? Thanks in advance for the help.

Jan-WIllem
  • 91
  • 13
  • It's hard to make sense of your question since a list of integers doesn't correspond with a TreeNode collection. Each node in a TreeView has it's own Nodes collection, and so on and so on. It's not a linear list. – LarsTech Feb 25 '19 at 20:12
  • If MySelectedNodeIndexes contains {2,4,7,1} I want the selected Nodes to be: this.Nodes[2].nodes[4].nodes[7].nodes[1]; – Jan-WIllem Feb 25 '19 at 20:16
  • @Jan-WIllem Okay now it's more clear. Put it into the question. Your list actually represent the index at each node level in order to get to the node you want. – Franck Feb 25 '19 at 20:18

1 Answers1

2

You can use a for loop to find the node base on the input index list. For example:

TreeNode GetNodeByIndexPath(TreeView treeView, int[] indexPath)
{
    var nodes = treeView.Nodes;
    TreeNode node = null;
    for (int i = 0; i < indexPath.Length; i++)
    {
        node = nodes[indexPath[i]];
        nodes = node.Nodes;
    }
    return node;
}

Example

var path = new int[] { 1, 1, 1 };
treeView1.SelectedNode = GetNodeByIndexPath(treeView1, path);
LarsTech
  • 80,625
  • 14
  • 153
  • 225
Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398