-1

I am making a To Do program. I have a checked list box there. I want to make every checked item deleted automatically. Here's the code that I am using to check if checked:

For i = 0 To CheckedListBox1.Items.Count - 1




            If CheckedListBox1.GetItemChecked(i) Then


            Else

            End If
        Next

How can I do that? Thanks

TIPD
  • 3
  • 4

2 Answers2

1

To remove Items from your ListBox, you can save items to be removed in your loop and then to delete it for example :

Dim itemsToRemove As New List(Of Object)

For i = 0 To CheckedListBox1.Items.Count - 1
    If CheckedListBox1.GetItemChecked(i) Then
        itemsToRemove.Add(CheckedListBox1.Items(i))
    End If
Next

For Each item As Object in itemsToRemove
    CheckedListBox1.Items.Remove(item)
Next
Gambi
  • 464
  • 4
  • 12
  • it says System.InvalidOperationException: 'Cross-thread operation not valid: Control 'CheckedListBox1' accessed from a thread other than the thread it was created on.' – TIPD Jan 16 '21 at 09:55
  • @gambi just enumerate the checkboxlist backwards and remove by index – Caius Jard Jan 16 '21 at 09:57
  • @TIPD, this might solve your problem : https://stackoverflow.com/questions/10775367/cross-thread-operation-not-valid-control-textbox1-accessed-from-a-thread-othe – Gambi Jan 16 '21 at 11:10
  • @CaiusJard, yes you are right, it works too. – Gambi Jan 16 '21 at 11:11
0

If you loop backwards then removing an item doesn't affect the part of the list you have yet to check

For i = CheckedListBox1.Items.Count - 1 to 0 Step -1
    If CheckedListBox1.GetItemChecked(i) Then
        CheckedListBox1.Items.RemoveAt(i)
    End If
Next

This won't prevent the cross thread exception you're getting; for that we really need to know why you're accessing this Control from a thread other than the thread that created it

Caius Jard
  • 72,509
  • 5
  • 49
  • 80