1

I need to remove parent node that not have child node and it's not a link to form but while processing always show "Collection was modified; enumeration operation may not execute." what is the best way to solve this?

 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
Erix_TK
  • 35
  • 1
  • 8

1 Answers1

0

You should use for loop instead of for each loop.
Because you can not modify the collection on which you are looping using foreach loop
More detail
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
Community
  • 1
  • 1
शेखर
  • 17,412
  • 13
  • 61
  • 117