-3

Possible Duplicate:
WPF ListBox: Item Removal

I am facing a really strange problem here. What i am trying to do is just removing items from listbox in WPF , so here is the code :

    private void button9_Click(object sender, RoutedEventArgs e)
    {
        if (listBox7.SelectedItems.Count > 0)
        {
            foreach (string item in listBox7.SelectedItems)
            {
                listBox7.Items.Remove(item);
            }
        }
    }

And that is not working at all , i always get error message [At the foreach loop] :

Collection was modified; enumeration operation may not execute.

Which is really annoying because i have been using that method for years. By the way i am fresh with WPF but i have a solid experience with C# so that should be okay for me.

EDIT : Well , i have figured out that i was talking about something else when i typed "using it for years"

Anyway here is the fix :

        List<string> removals = new List<string>();

        foreach (string item in listBox7.SelectedItems)
        {
            removals.Add(item);
        }

        foreach (string s in removals)
        {
            listBox7.Items.Remove(s);
        }
Community
  • 1
  • 1
R.Vector
  • 1,669
  • 9
  • 33
  • 41
  • 1
    How about searching for the error message before asking a question? – H.B. Jun 23 '12 at 16:43
  • 1
    This question has been asked and answered many times on SO. Please search before asking a question. – Gene S Jun 23 '12 at 16:52
  • 1
    That solution is kind of redundant, just use `listBox7.SelectedItems.`[`ToArray()`](http://msdn.microsoft.com/en-us/library/bb298736.aspx) or (`ToList()`) in the foreach. – H.B. Jun 23 '12 at 16:57
  • Ideally in WPF you should use data binding instead of manually adding or removing items directly on the ListBox. It takes a while to adjust to data binding and XAML/WPF, but it is quite nice once you get used to it. In that scenario, you would use an ObservableCollection (or preferably the class with the display values for the ListBox) instead. Here is one article on data binding: http://msdn.microsoft.com/en-us/library/ms752347.aspx – Ryan Jun 23 '12 at 18:54
  • Do not know a lot about WPF but here is a link that might help... http://stackoverflow.com/questions/4378099/wpf-listbox-item-removal – Gene S Jun 23 '12 at 16:50

1 Answers1

4

i have been using that method for years

I doubt that, you can never modify the collection you loop over with foreach. Either loop over a copy or use for.

(SelectedItems is a subset of Items, if you modify Items you modify SelectedItems)

H.B.
  • 166,899
  • 29
  • 327
  • 400