Search code examples
c#eventscheckedlistbox

ItemChecked event handler


I'm using the following code to limit the number of checked items in a CheckedListBox to 1:

        private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
    {
        if (checkedListBox1.CheckedItems.Count == 1)
        {
            Boolean isCheckedItemBeingUnchecked = (e.CurrentValue == CheckState.Checked);
            if (isCheckedItemBeingUnchecked)
            {
                e.NewValue = CheckState.Checked;
            }
            else
            {
                Int32 checkedItemIndex = checkedListBox1.CheckedIndices[0];
                checkedListBox1.ItemCheck -= checkedListBox1_ItemCheck;
                checkedListBox1.SetItemChecked(checkedItemIndex, false);
                checkedListBox1.ItemCheck += checkedListBox1_ItemCheck;
            }
            return;
        }
    }

But there are occasions where I need to clear all checked items. I'm using the code below to try to do that but the previous event is preventing that from working. How can I accomplish that? Thanks.

    public void ClearChecked()
    {
        foreach (int checkedItemIndex in checkedListBox1.CheckedIndices)
        {
            checkedListBox1.SetItemChecked(checkedItemIndex, false);
        }
    }

Solution

  • You could create a new variable indicating when the ItemCheck event should be ignored:

    private shouldIgnoreCheckEvent;
    
    public void ClearChecked()
    {
        this.shouldIgnoreCheckEvent = true;
    
        foreach (int checkedItemIndex in checkedListBox1.CheckedIndices)
        {
            checkedListBox1.SetItemChecked(checkedItemIndex, false);
        }
    
        this.shouldIgnoreCheckEvent = false;
    }
    

    and update your ItemCheck method to check if it should be ignored or not:

    private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
    {
        if (!this.shouldIgnoreCheckEvent && checkedListBox1.CheckedItems.Count == 1)
        {
            Boolean isCheckedItemBeingUnchecked = (e.CurrentValue == CheckState.Checked);
            if (isCheckedItemBeingUnchecked)
            {
                e.NewValue = CheckState.Checked;
            }
            else
            {
                Int32 checkedItemIndex = checkedListBox1.CheckedIndices[0];
                checkedListBox1.ItemCheck -= checkedListBox1_ItemCheck;
                checkedListBox1.SetItemChecked(checkedItemIndex, false);
                checkedListBox1.ItemCheck += checkedListBox1_ItemCheck;
            }
            return;
        }
    }