Search code examples
.netvb.netcontrolsdestroy

Destroying Controls VB.net


I'm having trouble destroying all of the controls after I've dynamically made them. I'm using this to destroy them:

For Each cControl In Me.Controls
            If (TypeOf cControl Is TextBox) Then
                Me.Controls.Remove(cControl)
            End If
        Next
        For Each cControl1 In Me.Controls
            If (TypeOf cControl1 Is CheckBox) Then
                Me.Controls.Remove(cControl1)
            End If
        Next

I've also used cControl.dispose() instead of Me.Controls.Remove(cControl).

Instead of going through and destroying all textboxes and checkboxes, it'll only destroy every other checkbox and the textboxes. If I switch the two For loops around, it'll be the other way around. Is there a fix for this? An explanation? Work around?


Solution

  • You shouldn't modify the Controls collection when you're iterating that collection. And you can join the too loops. This will solve your problem:

    Dim count As Integer = Me.Controls.Count
    
    For i As Integer = count -1 to 0 Step -1 
        Dim cControl As Control = Me.Controls(i)
    
        If (TypeOf cControl Is CheckBox OrElse TypeOf cControl Is TextBox) Then
            Me.Controls.Remove(cControl)
        End If
    Next