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);
}