Delete Checked Item from CheckedListView

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I want to iterate through a CheckedListView and delete the checked items ONLY.
Anybody know how to do this? Anybody know a rock solid way of doing this?
I have tried the following but get an exception

unhandled exception of type System.InvalidOperationException in
system.windows.forms.dll

Additionlal Info: The list that this enumerator is bound to has been
modified.
An enumerator can only be used if the list dosn't change.

Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnDelete.Click
Dim indexChecked, itemCount As Integer
Dim itemChecked As Object = ChkListBoxRoutines.CheckedItems

For Each itemChecked In itemChecked
ChkListBoxRoutines.Items.RemoveAt(indexChecked)
ChkListBoxRoutines.Refresh()
Next
End Sub
 
Wht is "itemChecked"? I usually fill a collection with items to remove
first, in order that I don't modify the collection while I'm iterating it.


Dim toRemove as New ArrayList

For Each theItem As <someclass> In <somecollectiontoremovefrom>
toRemove.Add ( theItem )
Next



For Each toRemove As <someclass> In toRemove
<somecollectiontoremovefrom>.Remove ( toRemove )
Next


(also please use option strict on - it makes your code a lot more
robust....)
 
Sorry Robin,
I don't understand your code too well
It's the <someclass> & <somecollectiontoremovefrom> I need help with.
Can you post a working example if you have time, I'ld really appreciate it.
marc
 
Something like this:


Private Sub deleteButton_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles deleteButton.Click

Dim toRemove As New ArrayList

For Each theItem As Object In CheckedListBox1.CheckedItems
toRemove.Add(theItem)
Next

For Each theItem As Object In toRemove
CheckedListBox1.Items.Remove(theItem)
Next

End Sub
 
thanks Robin Ill try it
marc

Robin Tucker said:
Something like this:


Private Sub deleteButton_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles deleteButton.Click

Dim toRemove As New ArrayList

For Each theItem As Object In CheckedListBox1.CheckedItems
toRemove.Add(theItem)
Next

For Each theItem As Object In toRemove
CheckedListBox1.Items.Remove(theItem)
Next

End Sub
 
Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnDelete.Click
Dim indexChecked, itemCount As Integer
Dim itemChecked As Object = ChkListBoxRoutines.CheckedItem­s
For Each itemChecked In itemChecked
ChkListBoxRoutines.Items.Remov­eAt(indexChecked)
ChkListBoxRoutines.Refresh()
Next
End Sub


Try using Remove() instead of RemoveAt(). The following worked for me

For Each itm As ListViewItem In lvwMain.CheckedItems
lvwMain.Items.Remove(itm)
Next

There was no need for a refresh - repainted itself after removing the
items.
 
Back
Top