Cannot remove items from ListBox

2019-01-29 02:20发布

When trying to run this method I get an error:

List that this enumerator is bound to has been modified. An enumerator can only be used if the list does not change.

foreach (var item in lstPhotos.SelectedItems)
{
    lstPhotos.Items.Remove(item);
}

How can I remove the selected items?

标签: c# listbox
2条回答
贼婆χ
2楼-- · 2019-01-29 02:54

the foreach loop doesn't allow you to modify the collection being enumerated. if you need to modify the collection use a for loop instead.

edit:

I am leaving my original answer above, but upon coding this it became apparent that a while loop is better suited to this problem because of the dynamic length of the SelectedItems property.

while(lstPhotos.SelectedItems.Length > 0)
{
    lstPhotos.Items.Remove(lstPhotos.SelectedItems[0];
}
查看更多
成全新的幸福
3楼-- · 2019-01-29 03:02
while(lstPhotos.SelectedItems.Count != 0)
{
    lstPhotos.Items.Remove(lstPhotos.SelectedItems[0]);
}
查看更多
登录 后发表回答