Gabor
Gabor

Reputation: 47

TreeNode index property by name

My question is the following. I need to get the Index of a TreeNode but I know just the name of this Node. Have you any idea, how can I get this property?

I'd like something same:

int treeIndex = treeView1.Nodes["myNode"].Index; 

If it's possible please show me a sample code.

Upvotes: 0

Views: 2382

Answers (2)

Sajeetharan
Sajeetharan

Reputation: 222657

You can do like this,

var result = treeView1.Nodes.OfType<TreeNode>()
                            .FirstOrDefault(node => node.Name.Equals("name"));

then access the index inside the Result.

Upvotes: 1

Tigran
Tigran

Reputation: 62265

You can define you custom Tree class.

Example using Indexers:

public class MyTreeView : TreeView 
{
    public int this[string nodeName] {
        var found = this.Nodes.FirstOrDefault(n=>n.Text == nodeName);
        return (found == null)?-1:found.Index;
    }
}

and after use this like:

var tree = new MyTreeView(); 
...
...

var coolNodeIndex = tree["MyCoolNode"].Index;

Upvotes: 0

Related Questions