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:

TPM

Well-known member
Joined
Dec 7, 2004
Messages
623
Location
CA
Programming Experience
3-5
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
 

TomPhillips

Active member
Joined
Feb 24, 2005
Messages
33
Programming Experience
10+
That was it. Thanks. My brain knew what it had to be but I couldn't put it together. You saved me some time.
 

jmcilhinney

VB.NET Forum Moderator
Staff member
Joined
Aug 17, 2004
Messages
14,322
Location
Sydney, Australia
Programming Experience
10+
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.
 
Top Bottom