我在尝试此代码时遇到上述错误.我试过给
just my code但没用. (这是默认的)
错误发生在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;