Accessing all the nodes in TreeView Control

前端 未结 7 1564
小蘑菇
小蘑菇 2020-11-27 22:27

I have a TreeView Control with set of nodes and child nodes. For example:

ROOT has A,B,C.

A has a1, a2, a3 and then

相关标签:
7条回答
  • 2020-11-27 23:18

    The following code is used for traversing a TreeView's nodes and returning only the leaf nodes:

    private IEnumerable<TreeNode> LeafNodes(TreeNode root)
    {
        Stack<TreeNode> stack = new Stack<TreeNode>();
        stack.Push(root);
        while (stack.Count > 0)
        {
            TreeNode current = stack.Pop();
            if (current.Nodes.Count == 0)
            {
                yield return current;
            }
            else
            {
                foreach (TreeNode child in current.Nodes)
                {
                    stack.Push(child);
                }
            }
        }
    }
    

    I use it for accessing the filenames in an explorer-like TreeView:

    private void LogFileNames()
    {
        //There may be more than one node at root level
        foreach (TreeNode rootNode in FileTreeView.Nodes)
        {
            //Print only filenames, not directories
            foreach (TreeNode leafNode in LeafNodes(rootNode))
            {
                Logger.Info(leafNode.Text);
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题