I have a TreeView control in my WinForms .NET application that has multiple levels of childnodes that have childnodes with more childnodes, with no defined depth. When a use
I have an extension method that I use for this:
public static IEnumerable<TreeNode> DescendantNodes( this TreeNode input ) {
foreach ( TreeNode node in input.Nodes ) {
yield return node;
foreach ( var subnode in node.DescendantNodes() )
yield return subnode;
}
}
It's C#, but could be referenced from VB or converted to it.
in .Net WindowsForm TreeView has Find()
method with the optional flag 'searchAllChildren'
.
in asp.net instead there isn't. to have the same result i use this (similar to Keith answer, but in input i use the TreeView)
public static IEnumerable<TreeNode> DescendantNodes2(this TreeView input)
{
foreach (TreeNode node in input.Nodes)
{
yield return node;
foreach (var subnode in node.DescendantNodes())
yield return subnode;
}
}
private static IEnumerable<TreeNode> DescendantNodes(this TreeNode input)
{
foreach (TreeNode node in input.ChildNodes)
{
yield return node;
foreach (var subnode in node.DescendantNodes())
yield return subnode;
}
}
Use recursion
Function GetChildren(parentNode as TreeNode) as List(Of String)
Dim nodes as List(Of String) = New List(Of String)
GetAllChildren(parentNode, nodes)
return nodes
End Function
Sub GetAllChildren(parentNode as TreeNode, nodes as List(Of String))
For Each childNode as TreeNode in parentNode.Nodes
nodes.Add(childNode.Text)
GetAllChildren(childNode, nodes)
Next
End Sub
I have converted the code to VB.Net
with this as a result:
Public Function FlattenBreadth(ByVal tree As TreeView) As List(Of TreeNode)
Dim nodes As New List(Of TreeNode)
Dim queue As New Queue(Of TreeNode)
Dim top As TreeNode
Dim nod As TreeNode
For Each top In tree.Nodes
queue.Enqueue(top)
Next
While (queue.Count > 0)
top = queue.Dequeue
nodes.Add(top)
For Each nod In top.Nodes
queue.Enqueue(nod)
Next
End While
FlattenBreadth = nodes
End Function