Remove Checked Items in a Checkedlistbox

Lanc1988

Contributor
Joined
Nov 27, 2003
Messages
508
Im trying to put some code in a button that will remove any items that are checked in a checkedlistbox..

here is the code I tried that isn't working:
Visual Basic:
        Dim i As Integer
        For i = 0 To listboxMiscGoals.CheckedItems.Count - 1
            listboxMiscGoals.Items.Remove(i)
        Next
 
Problem with removing items from a contolr's count is that after the first item is removed, the control's count changes...and this is probably causing a nice looking error message from your code.

Instead add the selected items to an array list and remove them from the array list.

Visual Basic:
        Dim itm As Object
        Dim items2Remove As New ArrayList()
        For Each itm In lstMiscGoals.SelectedItems
            items2Remove.Add(itm)
        Next

        Dim i As Integer
        For i = 0 To items2Remove.Count - 1
            lstMiscGoals.Items.Remove(itm)
        Next

opps! It's game time now. Bye
 
its still not removing the checked items.. only the item that is selected when the button is clicked.
 
You're right. I should have tested the snippet first...At least the Patriots won!

Give this a try - using the same logic as before:
Visual Basic:
        Dim i As Integer
        Dim items2Remove As New ArrayList()

        For i = 0 To lstMiscGoals.Items.Count - 1
            If lstMiscGoals.GetItemCheckState(i) = CheckState.Checked Then
                items2Remove.Add(i)
            End If
        Next

        For i = items2Remove.Count - 1 To 0 Step -1
            lstMiscGoals.Items.RemoveAt(items2Remove(i))
        Next

Or, in a more direct manner

Visual Basic:
        Dim i As Integer
        For i = lstMiscGoals.Items.Count - 1 To 0 Step -1
            If lstMiscGoals.GetItemCheckState(i) = CheckState.Checked Then
                lstMiscGoals.Items.RemoveAt(i)
            End If
        Next
 
Back
Top