I want to update both the contents and the checked state of items in a CheckedListBox on the ItemCheck event. It turns out that when removing an item that occurs before the checked item (the one that is being processed), both this checked item and the one after it will appear to be checked after the event finishes. To illustrate, here is some code that first populates a CheckedListBox with a sequence of integers (named checkedListBox), and then when an item is checked, removes this item, and also checks the previous item if it was even, or the following item if it was odd.
private void checkedListBox_ItemCheck(object sender, System.Windows.Forms.ItemCheckEventArgs e)
// get the currently checked index
int checkedItemIndex = (int)checkedListBox.Items[checkedListBox.SelectedIndex];
bool checkedEven = checkedItemIndex % 2 == 0 ? true : false;
// remove the event handler for now - it is triggered by SetItemCheckState
checkedListBox.ItemCheck -= new ItemCheckEventHandler(checkedListBox_ItemCheck);
// if it was an even number, check the previous index
// ie - checking 4 will result in 3 being checked
// else, check the following index
// ie - checking 5 will result in 6 being checked
if (checkedItemIndex > 1 && checkedEven)
checkedListBox.SetItemCheckState(checkedItemIndex - 1, CheckState.Checked);
else if (checkedItemIndex < checkedListBox.Items.Count - 1)
checkedListBox.ItemCheck += new ItemCheckEventHandler(checkedListBox_ItemCheck);
// remove the currently clicked index
// here is the code to populate the box
private void resetListBoxContents()
for (int i=0; i < 20; i++)
As you see, when checking 9, 9 is removed and 10 is checked. But when 4 is checked and removed, 3 becomes checked, as it should be, but so is 5, which should not be.
Any help in this matter would be greatly appreciated. Thanks!
General News Suggestion Question Bug Answer Joke Praise Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
Copyright © CodeProject
All Rights Reserved.