How to delete form controls in a loop

  • Thread starter Thread starter J L
  • Start date Start date
J

J L

I need to loop through a form's controls collection and delete some
based on type and location. I have tried For..Each and For i = 0 to
form.controls.count - 1 but when I delete any it messes up the loop.

What is the correct way to go about this. I thought this was answered
before but can not find it.

TIA,
John
 
Maybe this can help you:

For i As Integer = 0 To Me.Controls.Count - 1
Try
Me.Controls.Remove(Me.Controls(0))
Catch ex As Exception
End Try
Next

Greetz Peter
 
J said:
I need to loop through a form's controls collection and delete some
based on type and location. I have tried For..Each and For i = 0 to
form.controls.count - 1 but when I delete any it messes up the loop.

What is the correct way to go about this. I thought this was answered
before but can not find it.

TIA,
John

That loop will fail after you're removed about half of the controls

maybe something like:

while form.controls.count>1
form.Controls(0).dispose()
wend
 
JL,

The most secure method (the sample is without childcontrols), this allows as
well to keep selective some controls in it

\\\
For i As Integer = Me.Controls.Count - 1 to 0 step -1
Me.Controls.Remove(Me.Controls(0))
Next
///

I hope this helps,

Cor
 
Peter,
For i As Integer = 0 To Me.Controls.Count - 1
Try
Me.Controls.Remove(Me.Controls(0))
Catch ex As Exception
End Try
Next

Brrrrrrrrrrrrrrrr a not handled catched error.
You like the movie "the deerhunter" I assume

:-)

Cor
 
Cor,

it was early for me this morning and late last night so that's a double
excuse lol ;-)

Greetz Peter
 
Cor Ligthert said:
The most secure method (the sample is without childcontrols), this allows
as well to keep selective some controls in it

\\\
For i As Integer = Me.Controls.Count - 1 to 0 step -1
Me.Controls.Remove(Me.Controls(0))
Next
///

If all controls should be removed, you can call the 'Controls' collection's
'Clear' method instead of removing the controls in a loop.
 
Hi Cor,
Thank you that worked perfectly. I do not remove all controls but
processing the loop top-down did catch them all. Going the other way
only caught half the controls and then threw an error.

Thanks again,
John
 
Back
Top