سؤال

This is a .NET 3.5 Winforms project.

I'm having a weird error trying to programmatically check the checkboxes in checkboxlist.

for (int i = 0; i < 5; i++)
{
    cBListForming.Items.Add((i + 1).ToString());
    cBListForming.SetItemChecked(i, true);
}

So it adds 5 items, from 1 to 5, and then have the added checkboxes checked by default. Nothing surprising.

On the first iteration of the loop, everything works fine but on the second iteration (i == 1), SetItemChecked throws an exception.

System.ArgumentOutOfRange {"Index was out of range. Must be non-negative and less than the size of the collection.\r\nParameter name: index"}

I can see the first checkbox checked visually as well. The rest of them aren't because of the above exception.

This is pretty baffling. Just for testing purposes, I tried to add the items first, and programmatically check them later with a second loop, but still the same issue happens, even though the count of the checkbox is 5.

I tried using SetItemCheckState instead. Again, same issue.

I think I might've broken the CheckedListBox component itself, or some weird framework bug that I've encountered.

Any insights to what's going on here would be really appreciated.

هل كانت مفيدة؟

المحلول

This is pretty frustrating, but it actually did turn out to be a framework bug (Maybe Winforms Designer had a hiccup).

Removing and readding the checkedlistbox in the designer made it work. No other changes.

نصائح أخرى

Try the following:

for (int i = 0; i < 5; i++)
{
    cBListForming.Items.Add((i + 1).ToString(), true);
}

I'm assuming "cBListForming" is a checkbox list.

Check the number of checkboxlist you have. This might be the cause of the problem.

cBListForming.Count();
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top