如何从c#中删除列表框中的项目invalidoperationexception是未修改的集合被修改

问题描述:

protected void MoveOne()
        {
            int intNumberOfItems = strAvailableItems.Length;
            if (lsbAvailableList.SelectedItems != null)
            {
                foreach (var item in lsbAvailableList.SelectedItems)
                {

                    //if (lsbAvailableList.SelectedIndex < intNumberOfItems)
                    //{
                    int intLsbAvailableListIndex = lsbAvailableList.SelectedIndex; //get the index
                    lsbSelectedList.Items.Add(item);
                    lsbAvailableList.Items.RemoveAt(intLsbAvailableListIndex);
                    //lsbAvailableList.Items.Remove(lsbAvailableList.SelectedItems[intLsbAvailableListIndex]);
                    string strIndex = intLsbAvailableListIndex.ToString();
                    //int intLsbIndex = lsbAvailableList.Items.Add(item);
                    MessageBox.Show(strIndex);
                    //}
                 }
            }//
         }
        //-----------------------

这是一种过度简化的方法,用于安全地删除列表视图中当前选定的项目,而无需使用 .Tag s。

Here's an overly simplified way of how to safely remove the currently selected items in a list view, without the use of .Tags.
List<listviewitem> itemsToBeRemoved = new List<listviewitem>();
foreach (ListViewItem item in theListView.SelectedItems) {
    itemsToBeRemoved.Add (item);
}
foreach (ListViewItem lvi in itemsToBeRemoved) {
    theListView.Remove (lvi);
}



/ ravi


/ravi


您无法从中删除​​项目lsbSelectedList.Items 同时查询 lsbAvailableList.SelectedItems 。我建议您标记每个ListView项目(请参阅 .Tag 属性)并使用标记值来标识要删除的项目。



/ ravi
You can't remove items from lsbSelectedList.Items while simultaneously querying lsbAvailableList.SelectedItems. I suggest you tag each ListView item (see the .Tag property) and use the tagged values to identify the ones you want to remove.

/ravi


你可以用'foreach:
You can achieve this with 'foreach:
ListBox.SelectedObjectCollection selListItems = listBox1.SelectedItems;

foreach (var itm in selListItems.OfType<string>().ToList())
{
    listBox1.Items.Remove(itm);
}

通过将ListBox SelectedItems从ListBoxObjectCollection转换为List< string>,您可以在没有收集修改错误的情况下进行迭代和删除。



你也可以在'foreach循环中使用

By converting the ListBox SelectedItems from ListBoxObjectCollection to List<string>, you can iterate and remove without the collectio modification error.

You could also use

selListItems.OfType<object>().ToList()