c# – InvalidArgument =值’0’对’SelectedIndex’无效.参数名称:SelectedIndex

前端之家收集整理的这篇文章主要介绍了c# – InvalidArgument =值’0’对’SelectedIndex’无效.参数名称:SelectedIndex前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在尝试此代码时遇到上述错误.我试过给 just my code但没用. (这是默认的)

Here is my XML file

错误发生在cmbProduct_SelectedIndexChanged事件中.

cmbProduct --> comboBox
        cmbBrand   --> comboBox

全球

DataSet dsUpdate = new DataSet();

的Form_Load

dsUpdate.ReadXml(@"...\..\stock.xml");
        cmbProduct.DataSource = dsUpdate.Tables[0]
            .DefaultView.ToTable(true,"productname");//.DefaultView;
        cmbProduct.DisplayMember = "productname";
        cmbProduct.SelectedIndex = 0;

cmbProduct_SelectedIndexChanged

cmbBrand.Items.Clear();
        foreach (DataRow Row in dsUpdate.Tables[0].Select("productname='" + cmbProduct.Text + "'"))
        {
            //cmbBrand.SelectedIndex = i;
            cmbBrand.Items.Add(Row["brandname"].ToString());
            //i++;
        } 
        cmbBrand.SelectedIndex = 0; /*ERROR*/

请帮忙
提前致谢.

解决方法

问题是:

当你启动应用程序时,cmbBrand中没有项目,但cmbProduct会触发SelectedIndexChanged.

试试这个:

从Form1.Designer.cs中删除SelectedIndexChanged事件初始化.尝试找到以下行:

this.cmbProduct.SelectedIndexChanged += new System.EventHandler(this.cmbProduct_SelectedIndexChanged);

之后,当您使用xml文件中的数据填充DataSet时,初始化SelectedIndexChanged事件:

dsUpdate.ReadXml(@"...\..\stock.xml");
cmbProduct.DataSource = dsUpdate.Tables[0].DefaultView.ToTable(true,"productname");//.DefaultView;
cmbProduct.DisplayMember = "productname";
this.cmbProduct.SelectedIndexChanged += new System.EventHandler(this.cmbProduct_SelectedIndexChanged);
cmbProduct.SelectedIndex = 0;
原文链接:https://www.f2er.com/csharp/244440.html

猜你在找的C#相关文章