本文介绍了SelectedIndex与comboboxes不成功的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Windows窗体有三个组合框。 Combobox2引用了combobox1的子表,Combobox3引用了combobox2的子表。



我希望三个组合框在用户选择值之前不显示selectedItem。



首次展示表格时我有这个设置:





My Windows form has three comboboxes. Combobox2 references a child table of combobox1, and Combobox3 references a child table of combobox2.

I want the three comboboxes not to show a selectedItem until the user selects a value.

I have this set when the Form is first shown:


private void Form1_Shown(Object sender, EventArgs e)
 {

     this.comboBox1.SelectedIndex = -1;
     MessageBox.Show("You are in the Form.Shown event.");

 }



private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
 {
     if ((isClosing == false)&&(comboBox1.SelectedValue!=null))
     {
         try
         {
             String cb1Value = comboBox1.SelectedValue.ToString();
               //fill child table code goes here

         }
         catch (Exception ex)
         { MessageBox.Show(ex.Message, ex.GetType().ToString() + " comboBox1_SelectedIndexChanged"); }
         try
         { this.comboBox2.SelectedIndex = -1; }//end try
         catch (Exception ex)
         {
             MessageBox.Show(ex.Message, ex.GetType().ToString() + "cb2 ind comboBox1_SelectedIndexChanged ");
         }//end catch
     }//end if
 }//end comboBox1_SelectedIndexChanged





但是当我选择combobox1时,combobox2仍然有一个选定的值!



此外,当这些选择完成时,我不断收到以下错误消息:

对象引用未设置为对象的实例。



有谁知道发生了什么?在此先感谢!



But combobox2 still has a selected value when I make a selection for combobox1!

In addition, I keep getting the following error message when these selections are made:
"Object reference not set to an instance of an object."

Does anyone know what is happening? Thanks in advance!

推荐答案


if ((isClosing == false)&&(comboBox1.SelectedValue=null))





如果没有双等号,comboBox1.SelectedValue将被设置为null。



这将导致您的调用 String cb1Value = comboBox1.SelectedValue.ToString(); 引发对象引用未设置为对象错误的实例。



至于comboBox2未被重置,我不确定。将SelectedIndex设置为-1应该这样做。虽然,你真的不需要它在try / catch块中。



设置SelectedIndex = -1将永远不会抛出错误,除非comboBox2已被设置为null某点。



Without the double equal sign, comboBox1.SelectedValue will be set to null.

That would result in your call String cb1Value = comboBox1.SelectedValue.ToString(); raising an object reference not set to an instance of an object error.

As far as comboBox2 not being reset, I'm not sure. Setting the SelectedIndex to -1 should do that. Though, you really don't need it in a try/catch block.

Setting SelectedIndex = -1 will never throw an error unless comboBox2 has been set to null at some point.



这篇关于SelectedIndex与comboboxes不成功的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-29 04:37
查看更多