简体   繁体   English

无法从列表框删除项目

[英]Cannot remove items from ListBox

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? 如何删除所选项目?

while(lstPhotos.SelectedItems.Count != 0)
{
    lstPhotos.Items.Remove(lstPhotos.SelectedItems[0]);
}

the foreach loop doesn't allow you to modify the collection being enumerated. foreach循环不允许您修改要枚举的集合。 if you need to modify the collection use a for loop instead. 如果您需要修改集合,请使用for循环。

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. 我在上面留下了我的原始答案,但是通过编码,很明显,由于SelectedItems属性的动态长度,while循环更适合此问题。

while(lstPhotos.SelectedItems.Length > 0)
{
    lstPhotos.Items.Remove(lstPhotos.SelectedItems[0];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM