1

If no item is selected in the ListBox, then the code works fine.

If at least one item is selected in the ListBox, the foreach iteration breaks after the first item is evaluated. The exception is an InvalidOperationException and the detail shows Items collection has been modified.

foreach (object item in listBoxFiles.Items) //InvalidOperationException occurs
{
    if (listBoxFiles.SelectedItems.Contains(item)) 
    {
        //do nothing
    }
}

Edit: I was looking for something like ListBoxItem.IsSelected but it does not exist.

6
  • Are you sure //do nothing does nothing to the item collection? Commented Jul 23, 2012 at 6:45
  • Yes, in fact after removing all the codes inside the if-clause the error is still reproducible. Commented Jul 23, 2012 at 6:56
  • 1
    And it also throws if nothing is selected. Commented Jul 23, 2012 at 7:29
  • If I select an item and then deselect it, the exception is thrown. If I don't select/unselect any item, the exception will not be thrown. Strange behaviour, I think this is a bug in the WinForm library. Commented Jul 23, 2012 at 7:48
  • I created a form with a listbox and a button. The LB gets populated with some items and the click-Handler for the button executes your code above. The interation throws even if I never selected any items. Commented Jul 23, 2012 at 8:06

1 Answer 1

3

I can reproduce the problem. The access to SelectedItems seems to be changing Items, not the call to Contains. It should not do that. I have no explanation at the moment.

Workaround:

If you check if item is contained in SelectedItems you could right away iterate over SelectedItems instead. Another alternative would be to copy SelectedItems before the iteration like this:

List<object> selectedItems = new List<object>();
selectedItems.AddRange( listBoxFiles.SelectedItems.OfType<object>() );
Sign up to request clarification or add additional context in comments.

5 Comments

No need to make a full copy... you could just create a new reference outside of the iteration: ListBox.SelectedObjectCollection selectedItems = listBoxFiles.SelectedItems;
@drumboog - new reference does not work. I have to create a full copy (Eric's workaround).
Yes, a reference would still work on the same collection. (as expected)
@Robin Maben - A reference does not work. The get-accessor of SelectedItems seems to be doing something odd.
And that is not an assumption or an opinion, a did actually try it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.