Translating the second link provided by GSerg to vb.net.
Create a list to hold the controls you want to delete. You can loop through the all the controls and add certain ones to a list. This does not effect the Controls collection. I haven't seen InStr
used in a very long time. The .net .Contains
will probably do what you need.
The second loop loops through the lstToDelete
. This list is not effected by removing controls from the Controls collection.
The rule for For Each loops is don't effect the Collection you are looping through. You can change properties of the items in the collections. Just don't remove any items.
Sub CntrlKill(KillName As String)
Dim lstToDelete As New List(Of Control)
For Each c As Control In Controls
If c.Name.Contains(KillName) Then
lstToDelete.Add(c)
End If
Next
For Each c In lstToDelete
c.Dispose()
Next
End Sub
Or the backwards loop way.
Private Sub NukeControls(KillString As String)
For i = Controls.Count - 1 To 0 Step -1
If Controls(i).Name.Contains(KillString) Then
Controls(i).Dispose()
End If
Next
End Sub