Note: the Web Ms TreeView offers easy access to all checked TreeNodes: the WinForms TreeView TreeView does not.
So, you need a method to
get all the TreeNodes, and then you need to
select all the TreeNodes that are checked. This example uses the "classic" stack-based method that Eric Lippert advocates in order to avoid possible stack overflow with recursion:
public IEnumerable<TreeNode> GetNodes(TreeNodeCollection nodes)
{
var stack = new Stack<TreeNode>();
foreach (TreeNode node in nodes)
{
stack.Push(node);
}
while (stack.Count > 0)
{
var current = stack.Pop();
yield return current;
foreach (TreeNode child in current.Nodes)
{
stack.Push(child);
}
}
}
Then filter them to find the checked Nodes:
listBox1.Items.Clear();
var checkedNodes = GetNodes(treeView1.Nodes)
.Where(nd => nd.Checked)
.OrderBy(nd => nd.Text)
.ToArray();
listBox1.Items.AddRange(checkedNodes.ToArray());