cant remove items from a listbox

paulthepaddy

Well-known member
Joined
Apr 9, 2011
Messages
222
Location
UK
Programming Experience
Beginner
hi all, simple problem that i just cant figure out. here is the code

VB.NET:
For i = 0 To CheckedListBox_Car.CheckedItems.Count -1
            CheckedListBox_Car.Items.Remove(CheckedListBox_Car.CheckedItems.Item(i))
        Next
this code works fine as long as i dont remove ALL items, the error i am getting is index is out of bounds of the array, i have tried -1, -2 0 +1 +2 and all are still giving this error, i cant just create code for remove all as i wont always need all removed so i kinda of have to get this code or something similar to remove only checked items. the code below is code i have tried

VB.NET:
 CheckedListBox_Car.Items.Remove(CheckedListBox_Car.CheckedItems)

VB.NET:
 For Each Item In CheckedListBox_Car.checkedItems
 CheckedListBox_Car.Items.Remove(item)
Next

i just dont seee whats wrogn with the code i tried first.
 
When modifying the collection you are iterating you must loop backwards, ie from index last to first by Step -1.
For i = Me.CheckedListBox1.CheckedIndices.Count - 1 To 0 Step -1
    Me.CheckedListBox1.Items.RemoveAt(Me.CheckedListBox1.CheckedIndices(i))
Next
 
ahh right, please tell me if im wrong here, i like to explain back sometimes just to make sure i fully understand what is going on,.

say my item list is like this.

0: Hello
1: This
2: Is
3: My Item List

my code removes the first item so the list becomes this, but because I has already had value 0 it moves on to 1 skiping 0 in the list again??

0: This
1: Is
2: My Item List

sorry, i know this is of topic a little but i noticed you used me.checkedlistbox,, but why. i understand that me basicly mean in the current class eg
FORM_Image_Invoice, and i know you dont have to use it, but is their any advantages of using me over not using
 
Last edited:
my code removes the first item so the list becomes this, but because I has already had value 0 it moves on to 1 skiping 0 in the list again??
Right, that is that problem.
sorry, i know this is of topic a little but i noticed you used me.checkedlistbox,, but why. i understand that me basicly mean in the current class eg
FORM_Image_Invoice, and i know you dont have to use it, but is their any advantages of using me over not using
I usually qualify 'Me.' when referring to a current class member, since it limit the options given by intellisense auto-completion list thus requiring less typing. Using Me also helps getting on track faster when I (often) forget the control name. It is also makes the code more readable seeing that whatever referenced is a class member rather than local scope variable.
 
thanks for reply, and thanks for explaining me. seems it would be a good habit to get into i have noticed when calling subs i would just use say 'Clear_Price but somesime i go looking for variabes instead of subs depends on how tired i m lol. thanks for help. + rep
 
Back
Top