I have two ListBoxes, lstAvailableColors and lstSelectedColors. Between each listbox are two buttons, Add and Remove. When a color or colors is selected in lstAvailableCol
Maybe this is what you need
protected void btnAdd_Click(object sender, EventArgs e)
{
while(listBox1.SelectedIndex!=-1)
{
listBox1.Items.Remove(listBox1.SelectedItem);
}
}
You cannot modify a collection you are iterating on. In general, a good solution for this type of problem is to create an empty collection, and in your iterator, copy over all of the elements you do NOT want to remove; after the iteration is complete, replace the original collection with your new collection.
You cannot modify an collection while you are using an Enumerator for this collection, what the for each statement does.
You have to loop over the data with a normal for loop and then you can modify the collection, but you must be careful to correctly update the current index if you insert or remove elements. If you just add or remove elements and don't insert some, iterating from the last element to the first will do.
protected void btnAdd_Click(object sender, EventArgs e)
{
for (Int32 i = lstAvailableColors.Items.Count; i >= 0; i--)
{
ListItem item = lstAvailableColors.Items[i];
if (item.Selected)
{
lstSelectedColors.Items.Add(item);
lstAvailableColors.Items.Remove(item);
}
}
}
As the other answer mentioned, you can't remove items until you've completed the iteration. So perhaps something like this will be cleanest for you:
var itemsToRemove =
lstAvailableColors.Items.Cast<ListItem>().Where(i => i.IsSelected).ToArray();
foreach(ListItem item in itemsToRemove) lstAvailableColors.Remove(item);
Example on how to remove the selected Items. Here only the selected indices are taken and removed.
public void RemoveSelectedItems(ListBox listbox)
{
List<ListItem> items = GetSelectedItems(listbox);
foreach (var listItem in items)
{
listbox.Items.Remove(listItem);
}
}
public List<ListItem> GetSelectedItems(ListBox listbox)
{
int[] selectedIndices = listbox.GetSelectedIndices();
return selectedIndices.Select(index => listbox.Items[index]).ToList();
}
You can't modify a collection while you're iterating over it. Either iterate over a copy or use for, iterate in reverse and remove as you go down.