【发布时间】:2018-04-03 19:23:32
【问题描述】:
我有一个列表框,我想用这个列表框删除集合中的一个对象。但我只能删除第一项(选择索引 0)为什么?我解决不了这个问题
private void removeButton_Click(object sender, EventArgs e)
{
foreach (Student element in studentCollection) {
if (studentListbox.SelectedIndex != -1 && element.Name == studentListbox.SelectedItem.ToString())
{
studentCollection.Remove(element);
studentListbox.Items.RemoveAt(studentListbox.SelectedIndex);
}
break;
}
}
【问题讨论】:
-
需要注意的一点是,您不能在 foreach 循环中从
studentCollection中删除一个项目。 -
那么我如何从收藏中删除一个项目?如果我不能从 foreach 循环中删除,为什么我可以删除第一项?
-
foreach 循环在使用它时更改集合时不喜欢它。 for 循环不会介意,但您必须跟踪索引。另一种选择是使用循环查找项目,保存索引或对象引用,并在打破循环后删除。
-
你代替循环它。如果您改用 BindingList 并让 ListBox 使用 BindingList 作为数据源,则只需从源中删除项目即可。