Search code examples
c#nullreferenceexceptioncheckedlistbox

NullReferenceException after calling checkedListBox_ItemCheck


I have an exception here Application.Run(new Form1()) when I check not first item in CheckedListBox. Here's my code example

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    private List<bool> l = new List<bool>() { true, false, true, true, true};

    private void Form1_Load(object sender, EventArgs e)
    {
        for (int i = 0; i < 5; i++)
        {
            checkedListBox1.Items.Add(i);
        }
    }

    private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
    {
        for (int i = 0; i < 5; i++)
        {
            if (l[i] == true)
            {
                checkedListBox1.Items.Remove(i);
            }
        }
    }
}

Is there anybody who knows how to fix it? Thanks in advance.


Solution

  • The issue is that you're checking an item, firing the event associated with it (checkedListBox1_ItemCheck), and while the event is executing you are removing it from checkedListBox1. Therefore the event is no longer attached to an item, and the form throws an exception.

    You can confirm this by toggling the first check box which should behave fine.

    You need to rethink how you would like this to work. I don't know why you are designing it this way, but there is likely a better method. Why are you deleting items from checkedListBox1 on the check toggle? You can use an independent button to accomplish this.