user1358072
user1358072

Reputation: 447

listbox selecteditems cannot be removed due to using ItemsSource

I need you to help fix my issues. When I use listbox ItemSource in my code, selected items cannot be allowed to remove. Without using ListBox ItemsSource, the remove operation is working. Why? Please give me your soultion code. I need to include ItemsSource for the listbox. Thanks a million times! Oh yes I am using C# 4.5 and WPF.

    public SendEmail(List<string> items, ItemCollection needsItems)
    : this()
    {
        _needList = needsItems;

        lstNeeds.ItemsSource = _needList;
    }

  //Remove selected Items not working

 if (lstNeeds.SelectedItem != null)
    {

      for (int i = lstNeeds.SelectedItems.Count - 1; i >= 0; i--)
       {
         lstNeeds.Items.Remove(lstNeeds.SelectedItems[i]);
       }
    }

enter image description here

Upvotes: 1

Views: 574

Answers (2)

DonBoitnott
DonBoitnott

Reputation: 11025

Try this:

if (lstNeeds.SelectedItem != null)
{
    List<Int32> selIdx = new List<Int32>();
    foreach (var item in lstNeeds.SelectedItems)
        selIdx.Add(lstNeeds.Items.IndexOf(item);
    selIdx.Sort();  //necessary?
    for (Int32 idx = selIdx.Count - 1; i >= 0; i--)
    {
        lstNeeds.Items.RemoveAt(selIdx[i]);
    }
}

Upvotes: 0

Darren
Darren

Reputation: 70748

You're trying to remove an item from the collection you're iterating over.

Upvotes: 2

Related Questions