InvalidArgument =值'0'对'index'无效。 [英] InvalidArgument=Value of '0' is not valid for 'index'.

查看:444
本文介绍了InvalidArgument =值'0'对'index'无效。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的表单中有两个组合框,我在点击项目时添加和删除项目。但是当我从组合框中删除最后一项时出现此错误InvalidArgument ='0'的值对'index'无效。我尝试做一些解决方案,但仍然出现此错误。这是我从组合框中删除项目的代码。

I have two combo box in my form , I am adding and removing items on click on Items. But I got this error when I remove last item from combo box "InvalidArgument=Value of '0' is not valid for 'index'." I try to do some solution but still this error comes.Here is my code of removing item from combo box.

private void cbSelectedItems_MouseClick(object sender, MouseEventArgs e)
        {
            try
            {
                var s = (ComboBox)sender;
                if (s.SelectedItem != null)
                {
                    InvoiceItemBAL selectedRow = s.SelectedItem as InvoiceItemBAL;

                    Guid productId = selectedRow.id;
                    if (itemList.Where(q => q.id == productId).Count() > 0)
                    {
                        foreach (var item in itemList)
                        {
                            if (item.id == productId)
                            {
                                s.Items.Remove(item);
                                itemList.Remove(item);
                                break;
                            }
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Please Select Item First");
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Unhandled Exception");
                this.Close();
            }
        }

推荐答案

您无法从<$ c中使用的集合中删除项目$ c> foreach

You cannot remove items from a collection which is being used by a foreach
foreach (var item in itemList)
{
    if (item.id == productId)
    {
        s.Items.Remove(item);
        itemList.Remove(item);
        break;
    }
}

尝试这样做会改变收藏品,这是不允许的。

更改 foreach for 循环,向后遍历集合,它应该可以工作。

Trying to do that will alter the collection, and that is not allowed.
Change your foreach to a for loop, running backwards through the collection and it should work.


这篇关于InvalidArgument =值'0'对'index'无效。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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