我如何遍历一个列表框中的项目,然后删除这些项目吗? [英] How do I loop through items in a list box and then remove those item?

查看:203
本文介绍了我如何遍历一个列表框中的项目,然后删除这些项目吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到通过列表框试图循环时,然后删除项下面的错误。


  

名单,这枚举势必已被修改。一个枚举只能用于如果列表不变化。


 的foreach(字符串s在listBox1.Items)
{
    MessageBox.Show(多个);
    //做的东西有(S);
    listBox1.Items.Remove(多个);
}

我如何能够通过内容删除该项目仍循环?


解决方案

你想删除的所有项目?如果是这样,在的foreach 第一,那么就使用 Items.Clear()来之后将它们全部删除。

否则,也许循环向后通过索引:

  listBox1.BeginUpdate();
尝试{
  的for(int i = listBox1.Items.Count - 1; I> = 0;我 - ){
    //做listBox1.Items [I]    listBox1.Items.RemoveAt(ⅰ);
  }
} {最后
  listBox1.EndUpdate();
}

I'm getting the error below when trying to loop through a listbox and then remove the item.

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

foreach (string s in listBox1.Items)
{
    MessageBox.Show(s);
    //do stuff with (s);
    listBox1.Items.Remove(s);
}

How can I remove the item and still loop through the contents?

解决方案

Do you want to remove all items? If so, do the foreach first, then just use Items.Clear() to remove all of them afterwards.

Otherwise, perhaps loop backwards by indexer:

listBox1.BeginUpdate();
try {
  for(int i = listBox1.Items.Count - 1; i >= 0 ; i--) {
    // do with listBox1.Items[i]

    listBox1.Items.RemoveAt(i);
  }
} finally {
  listBox1.EndUpdate();
}

这篇关于我如何遍历一个列表框中的项目,然后删除这些项目吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆