1

我需要删除没有子节点的父节点,它不是表单的链接,但在处理时总是显示“集合已修改;枚举操作可能无法执行。” 解决这个问题的最佳方法是什么?

 Private Sub checkEmptyNode(ByVal T As TreeView)
    For Each menuNode As TreeNode In T.Nodes
        If menuNode.ChildNodes.Count > 0 Then
            For Each childNode As TreeNode In menuNode.ChildNodes
                If childNode.ChildNodes.Count > 0 Then
                    RemoveEmptyNode(childNode.ChildNodes)
                Else
                    If childNode.NavigateUrl.Trim = "" Then
                        childNode.Parent.ChildNodes.Remove(childNode)
                    End If
                End If
            Next
        Else
            If menuNode.NavigateUrl.Trim = "" Then
                T.Nodes.Remove(menuNode)
            End If
        End If
    Next
End Sub

Private Sub RemoveEmptyNode(ByVal TN As TreeNodeCollection)
    For Each subChildNode As TreeNode In TN
        If subChildNode.ChildNodes.Count > 0 Then
            RemoveEmptyNode(subChildNode.ChildNodes)
        Else
            If subChildNode.NavigateUrl.Trim = "" Then
                TN.Remove(subChildNode)
            End If
        End If
    Next
End Sub
4

1 回答 1

0

您应该使用for loop而不是for each loop.
因为您无法使用C# 中的foreach loop
更多详细信息来修改正在循环的集合
,为什么我不能在 foreach 循环中修改值类型实例的成员?
从循环中更改集合

Private Sub checkEmptyNode(ByVal T As TreeView)
    For i As Integer = 0 To T.Nodes.Count - 1
If T.Nodes(i).ChildNodes.Count > 0 Then
    For j As Integer = 0 To T.Nodes(i).ChildNodes.Count - 1


        If T.Nodes(i).ChildNodes(j).ChildNodes.Count > 0 Then
            RemoveEmptyNode(T.Nodes(i).ChildNodes(j).ChildNodes)
        Else
            If String.IsNullOrEmpty(T.Nodes(i).ChildNodes(j).NavigateUrl.Trim()) Then
                T.Nodes(i).ChildNodes(j).Parent.ChildNodes.Remove(T.Nodes(i).ChildNodes(j))
            End If
        End If
    Next
Else
    If String.IsNullOrEmpty(T.Nodes(i).NavigateUrl.Trim()) Then
        T.Nodes.Remove(T.Nodes(i))
    End If
End If
  Next
End Sub



Private Sub RemoveEmptyNode(TN As TreeNodeCollection)
For i As Integer = 0 To TN.Count - 1
    If TN(i).ChildNodes.Count > 0 Then
        RemoveEmptyNode(TN(i).ChildNodes)
    Else
        If String.IsNullOrEmpty(TN(i).NavigateUrl.Trim()) Then
            TN.Remove(TN(i))
        End If
    End If
Next
End Sub
于 2013-04-04T09:28:03.483 回答