问题
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.
回答1:
You can do like this,
var result = treeView1.Nodes.OfType<TreeNode>()
.FirstOrDefault(node => node.Name.Equals("name"));
then access the index inside the Result.
回答2:
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;
来源:https://stackoverflow.com/questions/24279097/treenode-index-property-by-name