c# - 从列表框中删除选定的项目

标签 c# listbox

我想这样做,但是列表框会在每次删除时发生变化,因此即使我尝试创建一个新对象,它也会抛出运行时异常。

我试过这样的:

ListBox.SelectedObjectCollection selectedItems = new ListBox.SelectedObjectCollection(lstClientes);
   selectedItems = lstClientes.SelectedItems;
if (lstClientes.SelectedIndex != -1)
{ 
    foreach (string s in selectedItems)
        lstClientes.Items.Remove(s);
}
else
    MessageBox.Show("Debe seleccionar un email");

最佳答案

您不能在迭代(使用 foreach)时修改集合。而是使用反向 for 循环:

ListBox.SelectedObjectCollection selectedItems = new ListBox.SelectedObjectCollection(lstClientes);
selectedItems = lstClientes.SelectedItems;

if (lstClientes.SelectedIndex != -1)
{ 
    for (int i = selectedItems.Count - 1; i >= 0; i--)
        lstClientes.Items.Remove(selectedItems[i]);
}
else
    MessageBox.Show("Debe seleccionar un email");

使用反向循环可确保您在删除它们后不会跳过任何内容。

关于c# - 从列表框中删除选定的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13149486/

相关文章:

c# - 在 Linux 上以 Mono 方式挂载 USB

c# - 使用c#设置excel的缩放大小

c# - 在 chrome 中滚动 ListBox 时回发

php - 单击发送按钮后列表框将数据发送到文本区域

Android TListBox 滚动不流畅

c# - 使用 caSTLe-windsor 的 MVC4 中 HttpClient 的生活方式

c# net2.0 Console App 将参数合并到一个字符串中

c# - 如何在不使用内联映射或多个 .ForMember 的情况下在 automapper 中映射嵌套对象?

arrays - 使用单指令填充 VB6 列表框

C# 当我在列表框中选择一个项目时,我应该使用哪个事件在文本框中显示数据?