TreeNode index property by name

淺唱寂寞╮ 提交于 2019-12-25 06:45:38

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!