Removing all controls of a type.

TomPhillips

Active member
Joined
Feb 24, 2005
Messages
33
Programming Experience
10+
Removing all controls of a type. RESOLVED

I am placing ListBox controls on a form in rows and columns. I then want to remove them and replace them with new ones. When I use code like this:

For Each ctrl As Control In Me.Controls
If TypeOf ctrl Is ListBox Then
ctrl.Dispose()
End If
Next

only every other box gets removed. I can keep running the block over and over till all boxes are gone, but why is this happening and how can I just dispose of all the ListBoxes on a form at once?
 
Last edited:
I delive the answer is by disposing the control your screwing the for each up. For each control loops through useing the controls indexs, an example will help explain;
You have 3 listboxes, there indexes are 0-2. 0 goes through your for each loop and is disposed, now 1's index is 0. But your loop doesn't know that so it move onto control index 1 (which is now your 3rd listbox). What you can do is instead of a for each you could do this:

VB.NET:
dim i as integer = 0
while i < me.controls.count
if TypeOf me.controls(i) is listbox Then
me.controls(i).dispose()
Else
i+=1
end if
end while

Note that it'll only increment the control index if the current control isn't deleted.

TPM
 
Whenever deleting multiple objects from a collection, I always use a for loop counting backwards:
VB.NET:
For i as Interger = collection.Count - 1 To 0 Step -1
	collection.RemoveAt(i)
Next
This way, it doesn't matter whether you want to delete all items or just some, as the only items whose indices are affected have already been through the loop.
 
Back
Top