InvalidArgument =值'0'对于'索引'无效.参数名称:索引 [英] InvalidArgument=Value of '0' is not valid for 'index'. Parameter name: index

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

问题描述

private void button1_Click(object sender, EventArgs e)
        {
            int b = comboBox1.Items.Count;
            for (int i = 0; i <= b; i++)
                if (comboBox1.Text == comboBox1.Items[i])

                    MessageBox.Show("Already exist");
                    else
                {
            string a = comboBox1.Text;
           comboBox1.Items.Add(a);
                }
        }

推荐答案

这是一个简单的数学问题:
It''s a simple math problem:
int b = comboBox1.Items.Count;
for (int i = 0; i <= b; i++)

如果计数等于零,则测试将通过,并且循环将执行一次,以检索不存在的元素.
试试:

if the count is equal to zero, then your test will pass, and the loop will be executed once, to retrieve an element that does not exist.
Try:

int b = comboBox1.Items.Count;
for (int i = 0; i < b; i++)


private void button1_Click(object sender, EventArgs e)
        {
            int b = comboBox1.Items.Count;
            bool doesExist = false;

            for (int i = 0; i < b; i++)
            {
                if (comboBox1.Items[i].ToString() == comboBox1.Text)
                {
                    MessageBox.Show("Already exist");
                    doesExist = true;
                    break;
                }
            }
            if (!doesExist)
            {
                string a = comboBox1.Text;
                comboBox1.Items.Add(a);
            }
        }


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

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