本文介绍了如何从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);
                    //}
                 }
            }//
         }
        //-----------------------

推荐答案

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



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是未修改的集合被修改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 18:37