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

Gar*_*ary 0 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;
Run Code Online (Sandbox Code Playgroud)

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

并且SelectedIndex被设置为-1。将值设置为和integer之间的任何其他值都可以正常工作。为什么会发生这种情况?15

感谢您的任何建议。

mcs*_*vio 5

这段代码看起来没问题。我怀疑您有一个 SelectedIndexChanged 事件处理程序,并且其中的某些内容引发了异常。Microsoft 文档说 0 是要指定的有效索引。如果组合框中没有任何元素,您应该收到 ArgumentOutOfRangeException。