Handling CheckedListBox ItemCheck event in C#

2015/11/19 10:16
Common problem handling ItemCheck event in CheckedListBox control is the fact that when the event is fired the object's state change is not finalized.
If within the ItemCheck event handling function we try to get the CheckedListBox item's check state using the most common methods like getting collection of all checked items
foreach (object obj in checkedListBox1.CheckedItems) { // some code here ... }
only the previously checked items will be included in the collection.

One of the solution for handling ItemCheck event is using the event's argument "NewState" property. Example code:
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
   if (e.NewValue == CheckState.Checked)
      {
         // some code here to work with the recently checked Item ...
      }
}
The C# example solution (VisualStudio 2010) available for downloading presents the CheckedListBox CheckedItems property and ItemCheck event.

The function ListCheckedItems() use CheckedItemCollection and is linked to both the button "Checked ?" and inside the ItemCheck event handling.
private void ListCheckedItems()
{
   string checkedItems = "";
   foreach (object obj in checkedListBox1.CheckedItems)
   {
      checkedItems += obj.ToString();
      checkedItems += "\n";
   }
   MessageBox.Show("The following Items are checked:\n" + checkedItems, "Function: ListCheckedItems");
}
When an item is checked the function ListCheckedItems() shows the list of the checked items as they are visible via the CheckedItems property, then using the ItemCheck event argument the new checked state of the checked item is shown.
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
   ListCheckedItems();
   if (e.NewValue == CheckState.Checked)
   {
      string ItemText = checkedListBox1.GetItemText(checkedListBox1.Items[e.Index]);
      ItemText = ItemText.Insert(0, "\" ");
      ItemText += " \"";
      string message = "ITEM " + ItemText + " has been checked.";
      MessageBox.Show(message, "On CheckedListBox ItemChecked event");
   }
}
The complete Visual Studio 2010 C# project solution is attached here for your reference - CSharp Example