Remove Empty Nodes from C# TreeView: Quick Guide

In the C# TreeView control, you can quickly delete empty nodes using a recursive method. Here is an example code:

private void RemoveEmptyNodes(TreeNodeCollection nodes)
{
    // 从后向前遍历节点集合,以便在移除空节点后索引不会变化
    for (int i = nodes.Count - 1; i >= 0; i--)
    {
        TreeNode node = nodes[i];
        
        // 递归删除子节点的空节点
        RemoveEmptyNodes(node.Nodes);
        
        // 如果当前节点是空节点,则移除
        if (node.Nodes.Count == 0)
        {
            nodes.Remove(node);
        }
    }
}

Usage instructions:

// 调用方法开始删除空节点
RemoveEmptyNodes(myTreeView.Nodes);

In the above code, the RemoveEmptyNodes method takes a TreeNodeCollection parameter, which represents the collection of nodes to remove empty nodes from. Inside the method, first, the empty nodes of the child nodes are removed in a recursive way, and then it checks if the current node is an empty node and removes it from the node collection.

bannerAds