简体   繁体   English

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

[英]Delete selected items from listbox

I want to do that but, the listbox changes on every deletion, so it throws runtime exception even if I tried to do a new object.我想这样做,但是列表框在每次删除时都会更改,因此即使我尝试创建一个新对象,它也会引发运行时异常。

I tried like this:我试过这样:

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");

You can't modify a collection while iterating (using a foreach ) through it.在迭代(使用foreach )时不能修改集合。 Instead use a reverse for loop:而是使用反向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");

Using a reverse loop ensures you don't skip over any after removing them.使用反向循环可确保您在删除它们后不会跳过任何内容。

selectedItems = lstClientes.SelectedItems;

This line does not create a new collection, but sets a reference to the one in a listbox.此行不会创建新集合,而是设置对列表框中的集合的引用。 So you are iterating through a collection and try to remove items from it at once.因此,您正在遍历一个集合并尝试立即从中删除项目。 It is not possible这不可能

You could use this, for example:您可以使用它,例如:

foreach (string s in lstClientes.SelectedItems.OfType<string>().ToList())
   lstClientes.Items.Remove(s);

Simple just like this:就像这样简单:

while (lst.SelectedItems.Count > 0)
{
   lst.Items.Remove(lst.SelectedItems[0]);
}
lst.Items.Remove(lst.Items[lst.SelectedIndex]);

You can use this if you don't want to loop如果您不想循环,可以使用它

Note: This only works to remove 1 item (multiple selections it will only remove the first selected item)注意:这仅适用于删除 1 个项目(多选它只会删除第一个选定的项目)

To build on Patrick's answer I tend to use a reverse index removal as it retains the index of items pending removal while they're being removed without removing identical items.为了建立帕特里克的回答,我倾向于使用反向索引删除,因为它保留了待删除项目的索引,而它们被删除而不删除相同的项目。

private void BtnDelete_Click(object sender, EventArgs e) {
    if (listBox.SelectedIndex == -1) {
        return;
    }

    // Remove each item in reverse order to maintain integrity
    var selectedIndices = new List<int>(listBox.SelectedIndices.Cast<int>());
    selectedIndices.Reverse();
    selectedIndices.ForEach(index => listBox.Items.RemoveAt(index));
}

I found better solution.我找到了更好的解决方案。

        if (listBoxIn.SelectedItems.Count != 0)
        {
            while (listBoxIn.SelectedIndex!=-1)
            {
                listBoxIn.Items.RemoveAt(listBoxIn.SelectedIndex);                  
            }
        }

I encountered this same problem today and wanted something a bit cleaner, and came up with this Linq solution:我今天遇到了同样的问题,想要一些更清洁的东西,并提出了这个 Linq 解决方案:

foreach (int index in myListBox.SelectedIndices.Cast<int>().Select(x => x).Reverse())
    myListBox.Items.RemoveAt(index);

Basically the same as Patrick's solution of iterating backwards and removing selected items.与 Patrick 的向后迭代和删除选定项目的解决方案基本相同。 However instead of iterating backwards, we reverse the list of items to remove and iterate forwards.然而,我们不是向后迭代,而是反转要删除的项目列表并向前迭代。 We no longer iterate over the original enumeration, so we are allowed to remove items within the foreach.我们不再遍历原始枚举,因此我们可以删除 foreach 中的项目。

This is the most easiest way to remove selected items这是删除所选项目的最简单方法

 for(int v=0; v<listBox1.SelectedItems.Count; v++) {
            listBox1.Items.Remove(listBox1.SelectedItems[v]);
        }

This works for multiple and single selections in WPF.这适用于 WPF 中的多个和单个选择。

while (xListBox.SelectedItems.Count > 0)
{
    xListBox.Items.RemoveAt(SavedItemsListBox.SelectedIndex);
}

Create a global variable:创建一个全局变量:

public partial class Form1 : Form
    {

        Int32 index;
    }

Then at the selected index change save that index in the var you defined :然后在选定的索引更改处将该索引保存在您定义的 var 中:

 private void lsbx_layers_SelectedIndexChanged(object sender, EventArgs e)
        {

           layerindex = lsbx_layers.SelectedIndices[0];//selected index that has fired the event
         }

Finally ,remove the element :最后,删除元素:

 lsbx_layers.Items.RemoveAt(Layerindex);

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

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