Deleting Items from a WindowsForms CheckedListBox

I've been working on a new utility today, and it required me to interact with a WindowsForms CheckedListBox control. It took me about 20 minutes to figure this out, but if you delete a SelectedItem from the source list, you MUST change the SelectedIndex before you delete the item and rebind. Otherwise you'll through an IndexOutOfRange exception with a non-existent stack trace.

Example:

1    Private Sub Button_Delete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button_Delete.Click

2 Dim selectedindex As Integer = CheckedListBox1.SelectedIndex
3 CheckedListBox1.SelectedIndex = selectedindex - 1
4 If CheckedListBox1.CheckedItems.Count = 0 Then
5 key.Entries.RemoveAt(selectedindex)
6 Else
7 For Each entry As RegistryEntry In CheckedListBox1.CheckedItems
8 key.Entries.Remove(entry)
9 Next
10 End If
11
12 ReSort()
13 CheckedListBox1.DataSource = Nothing
14 CheckedListBox1.DisplayMember = "Value"
15 CheckedListBox1.DataSource = key.Entries
16 End Sub
Hope that saves someone some troubleshooting time.

No Comments