添加项后将ComboBox SelectedIndex设置为0会引发异常

时间:2014-01-10 16:04:23

标签: c# combobox

有一天,即使是最简单的事情也行不通。 TGIF。请考虑以下代码来填充使用设计器放置在表单上的combobox

   cboDisposition.Items.Add("Choose");  
   cboDisposition.Items.Add("Use as Is");  
   cboDisposition.Items.Add("Rework");  
   cboDisposition.Items.Add("Scrap");  
   cboDisposition.Items.Add("Return to Vendor");  
   cboDisposition.Items.Add("Void");  
   cboDisposition.DropDownStyle = ComboBoxStyle.DropDownList;

   cboDisposition.SelectedIndex = 0;

设置SelectedIndex会导致异常:ex = {"Object reference not set to an instance of an object."}

并且SelectedIndex设置为-1。将值设置为integer1之间的任何其他5工作正常。为什么会这样?

感谢您的任何建议。

2 个答案:

答案 0 :(得分:4)

此代码看起来不错。我怀疑你有一个SelectedIndexChanged的事件处理程序,并且那里有东西抛出异常。 Microsoft文档说0是要指定的有效索引。如果组合框中没有任何元素,则应该收到ArgumentOutOfRangeException。

答案 1 :(得分:0)

最后,使用CreateControl方法刷新组合框中的选项列表。

cboDisposition.CreateControl();

cboDisposition.SelectedIndex = 0;

然后它不会抛出错误。

相关问题