0

This code isn't working. It doesn't raise an exception or even do anything visible.

private void RemoveSelectedFiles()
{
    lstPhotos.Items.Remove(lstPhotos.SelectedItems);
}

How can I remove the selected items from a ListBox?

bernhof
  • 6,219
  • 2
  • 45
  • 71
Sergio Tapia
  • 40,006
  • 76
  • 183
  • 254

1 Answers1

1

You have to remove one item at a time.

EDIT - as @Smith pointed, the code would raise an exception because ListBox.SelectedItems is bound to the Items collection. Removing a selected item from Items will effectively remove it from SelectedItems too, thus breaking the enumeration. Now we enumerate an independent list containing the selected items:

private void RemoveSelectedFiles()
{
    var selectedItems = new List<object>(lstPhotos.SelectedItems);

    foreach (object item in selectedItems) 
        lstPhotos.Items.Remove(item);
}
Humberto
  • 7,117
  • 4
  • 31
  • 46