Click here to Skip to main content
13,006,281 members (77,587 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


8 bookmarked
Posted 18 Jan 2012

Retrieving TreeView nodes as IEnumerable

, 24 Jan 2012
Rate this:
Please Sign up or sign in to vote.
Extension method to make it easy to retrieve all nodes of a TreeView control.

To retrieve all nodes from a TreeView control, the recursion method is normally used. But I prefer to use a Queue, implementing the BFS algorithm. I want to propose a simple extension method that provides you with an easy way to retrieve all nodes from a TreeView without recursion, as a simple IEnumerable.

public static class TreeViewExtension
    public static IEnumerable<TreeNode> AllTreeNodes(this TreeView treeView)
        Queue<TreeNode> nodes = new Queue<TreeNode>();
        foreach (TreeNode item in treeView.Nodes)
        while (nodes.Count > 0)
            TreeNode node = nodes.Dequeue();
            yield return node;
            foreach (TreeNode item in node.Nodes)

You can use this code as follows:

foreach(var node in treeView1.AllTreeNodes())

or in LINQ expressions:

.Aggregate<TreeNode, String>("", (s, n) => s + n.Name + Environment.NewLine);

The result of the last code example is:



This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Software Developer DevelopEx
Ukraine Ukraine
No Biography provided

You may also be interested in...

Comments and Discussions

QuestionExcelente Pin
Member 127631239-Oct-16 17:45
memberMember 127631239-Oct-16 17:45 
QuestionThoughts Pin
PIEBALDconsult18-Jan-12 6:04
memberPIEBALDconsult18-Jan-12 6:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170628.1 | Last Updated 24 Jan 2012
Article Copyright 2012 by intrueder
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid