C# TreeView Node Traversal Guide
One way to traverse all nodes is to use recursion, here is an example:
private void TraverseTreeViewNodes(TreeNodeCollection nodes)
{
foreach (TreeNode node in nodes)
{
// 处理当前节点
Console.WriteLine(node.Text);
// 递归遍历子节点
TraverseTreeViewNodes(node.Nodes);
}
}
// 用法示例
TraverseTreeViewNodes(treeView1.Nodes);
In the code above, the TraverseTreeViewNodes method takes a TreeNodeCollection parameter to iterate through all the nodes in that collection. Within the method, a foreach loop is used to iterate through each node and perform operations on each node, such as outputting the node’s text. Then, recursive calls to the TraverseTreeViewNodes method are used to iterate through the child node collection of the current node, achieving the goal of traversing all nodes.