title: WPF : remove item from listbox
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/4378099/wpf-listbox-item-removal">WPF ListBox: Item Removal</a>  </p>
  </blockquote>
  
  
  
  <p>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 :</p>
  
  <pre><code>    private void button9_Click(object sender, RoutedEventArgs e)
      {
          if (listBox7.SelectedItems.Count &gt; 0)
          {
              foreach (string item in listBox7.SelectedItems)
              {
                  listBox7.Items.Remove(item);
              }
          }
      }
  </code></pre>
  
  <p>And that is not working at all , i always get error message [At the foreach loop] :</p>
  
  <pre><code>Collection was modified; enumeration operation may not execute.
  </code></pre>
  
  <p>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.</p>
  
  <p>EDIT :
  Well , i have figured out that i was talking about something else when i typed "using it for years"</p>
  
  <p>Anyway here is the fix :</p>
  
  <pre><code>        List&lt;string&gt; removals = new List&lt;string&gt;();
  
          foreach (string item in listBox7.SelectedItems)
          {
              removals.Add(item);
          }
  
          foreach (string s in removals)
          {
              listBox7.Items.Remove(s);
          }
  </code></pre>