简体   繁体   English

从当前选定的选项中循环浏览树视图的节点

[英]Loop through nodes of tree view from current selected

I have a tree view that has been built fine with no issues. 我有一个树状结构,构建良好,没有任何问题。

Is their a way to start looping through the nodes at the current selected node instead of looping through all of them? 他们是否有办法开始遍历当前所选节点上的节点,而不是遍历所有节点?

TreeNodeCollection nodes = treeView.Nodes;
   foreach (TreeNode n in nodes)
   {

   }

You could use an extension method to do this: 您可以使用扩展方法来执行此操作:

public static class TreeViewEx
{
    public static List<TreeNode> GetAllNodes(this TreeNode Node)
    {
        List<TreeNode> list = new List<TreeNode>();
        list.Add(Node);
        foreach (TreeNode n in Node.Nodes)
        list.AddRange(GetAllNodes(n));
        return list;
    }
}

Use it like this: 像这样使用它:

TreeNode node = myTree.SelectedNode;
List<TreeNode> list = node.GetAllNodes();

I should point out that the returned List will include the starting node (the one you selected originally). 我应该指出,返回的List将包括起始节点(您最初选择的那个节点)。

This may help head you in the right direction you would need to check each child node to see if they had children: 这可以帮助您朝正确的方向前进,您需要检查每个子节点以查看它们是否有子节点:

    TreeView treeView = new TreeView();
    TreeNode parentNode = treeView.SelectedNode;

    if (parentNode.GetNodeCount(true) > 0)
    {
        foreach (TreeNode childNodes in parentNode.Nodes)
        {
            //// do stuff with nodes.
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM