删除没有子节点的父节点,它不是ASP.NET中的表单

时间:2013-04-04 09:07:10

标签: asp.net

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

 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

1 个答案:

答案 0 :(得分:0)

您应该使用for loop代替for each loop
因为您无法使用foreach loop修改要循环的集合
更多细节
In C#, why can't I modify the member of a value type instance in a foreach loop?
Changing a Collection from within a loop

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