开发者

How do I remove muItiple items from a ListBox? [duplicate]

This question already has answers here: 开发者_JS百科 Cannot remove items from ListBox (2 answers) Closed 9 years ago.

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?


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜