Adam M.
Adam M.

Reputation: 1

For Each Control

I have a problem when I'm using the For Each loop:

If I Run this loop, I can see all (let's suppose) 100 controls.

For each Btn as Control in Controls
   If TypeOf Btn Is Button then
      If instr(1,Btn.Name,"Test",0) Then Debug.Print(Btn.name)
   End If   
Next

But if I need to delete them, the loop seems confusing looping through the controls and it skips some...

For each Btn as Control in Controls
   If TypeOf Btn Is Button then
      If instr(1,Btn.Name,"Test",0) Then Controls.Remove(Btn)
   End If   
Next

I tried to restart the loop each time I remove a control, but the solution is not so... elegant.

Is there anyway to fix this problem ?

Upvotes: 0

Views: 638

Answers (1)

user10216583
user10216583

Reputation:

Try:

For i As Integer = Controls.Count - 1 To 0 Step -1
    If TypeOf Controls(i) Is Button AndAlso Controls(i).Name.StartsWith("Test") Then
        Controls.RemoveAt(i) ' or Controls(i).Dispose()
    End If
Next

... or

For Each c In Controls.OfType(Of Button).
    Where(Function(x) x.Name.StartsWith("Test")).ToList
    Controls.Remove(c) 'Or c.Dispose()
Next

... or

For Each c In Controls.OfType(Of Button).
    Where(Function(x) x.Name.StartsWith("Test")).Reverse()
    Controls.Remove(c) 'Or c.Dispose()
Next

... to remove an object while looping it's collection.

Upvotes: 1

Related Questions