如何从c#中删除列表框中的项目invalidoperationexception是未修改的集合被修改 [英] How do you remove an item from a listbox in c# invalidoperationexception was unhandled collection was modified

查看:91
本文介绍了如何从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()


这篇关于如何从c#中删除列表框中的项目invalidoperationexception是未修改的集合被修改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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