user1805445
user1805445

Reputation: 159

Index was outside the bounds of the array in CheckedListBox

I am getting an index error on my else if statement but I'm unable to find the reason for it.

What I am doing is going through a CheckedListBox, if no values are checked print an error else show the selected values in a MessageBox.

Can anybody help me? Thank you!

for (int i = 0; i < checkedListBox1.Items.Count; i++)
if (checkedListBox1.CheckedItems.Count == 0) 
{
  Empty.SetError(checkedListBox1, "Please select at Least One");
  return;
}
else if (checkedListBox1.GetItemChecked(i))
{
   MessageBox.Show(checkedListBox1.CheckedItems[i].ToString());
}

Upvotes: 0

Views: 277

Answers (4)

Tim Schmelter
Tim Schmelter

Reputation: 460228

Move the Count-ckeck before the loop:

 if (checkedListBox1.CheckedItems.Count == 0)
 {
    Empty.SetError(checkedListBox1, "Please select at Least One");
    return;
 }

But the important part is that you are looping all items. Then you check for every item if it is checked with GetItemChecked. That's fine, but then you use checkedListBox1.CheckedItems[i] which doesn't contain all items but only the checked items. That's why you get the Index was outside the bounds error.

Instead you just need to use that collection instead of looping all:

for(int i = 0; i < checkedListBox1.CheckedItems.Count; i++)
{
    MessageBox.Show(checkedListBox1.CheckedItems[i].ToString());
}

Upvotes: 1

Atanas Desev
Atanas Desev

Reputation: 868

Why are you checking for CheckedItems.Count inside the for cycle?

Take the first part of the If clause outside of the For cycle.

At the end your code can look like that:

 if (checkedListBox1.CheckedItems.Count == 0)
 {
    Empty.SetError(checkedListBox1, "Please select at Least One");
 }
 for (int i = 0; i < checkedListBox1.Items.Count; i++)
   if (checkedListBox1.GetItemChecked(i))
   {
     MessageBox.Show(checkedListBox1.Items[i].ToString());
   }

Upvotes: 0

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73492

checkedListBox1.CheckedItems[i] is the problem. You loop through all the items, but indexing CheckedItems. So when you have 10 items and checked 2nd item and 8th item, CheckedItems will have only two items but you'll be accessing CheckedItems[7] that's why you get the exception.

Use CheckedItems collection to access checked items directly.

if (checkedListBox1.CheckedItems.Count == 0)
{
    Empty.SetError(checkedListBox1, "Please select at Least One");
    return;
}
foreach (var checkedItem in checkedListBox1.CheckedItems)
{
    MessageBox.Show(checkedItem.ToString());
}

Upvotes: 1

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101701

You should change

i < checkedListBox1.Items.Count;

To:

i < checkedListBox1.CheckedItems.Count;

Upvotes: 1

Related Questions