[英]Setting ComboBox SelectedIndex to 0 after adding items throws exception
在那些日子里,即使最简单的事情也不起作用。 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
。 将值设置为1
到5
之间的任何其他integer
可以正常工作。 为什么会这样呢?
感谢您的任何建议。
此代码看起来不错。 我怀疑您有一个用于SelectedIndexChanged的事件处理程序,并且其中存在引发异常的事件。 Microsoft文档说0是要指定的有效索引。 如果组合框中没有任何元素,则应改为收到ArgumentOutOfRangeException。
最后,使用CreateControl方法刷新组合框中的选项列表。
cboDisposition.CreateControl();
cboDisposition.SelectedIndex = 0;
这样就不会抛出错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.