Reputation: 495
It's one of those days when even the simplest things don't work. TGIF. Consider the following code to populate a combobox
which has been placed on a form using the designer:
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;
Setting the SelectedIndex
causes an exception: ex = {"Object reference not set to an instance of an object."}
and the SelectedIndex
is set to -1
. Setting the value to any other integer
between 1
and 5
works fine. Why is this happening?
Thanks for any advice.
Upvotes: 0
Views: 6624
Reputation: 1
At the end, use the CreateControl method to refresh the list of options in the combo box.
cboDisposition.CreateControl();
cboDisposition.SelectedIndex = 0;
Then it won't throw an error.
Upvotes: 0
Reputation: 1098
This code looks OK. I suspect that you have an event handler for SelectedIndexChanged, and that something in there is throwing the exception. The Microsoft docs say that 0 is a valid index to specify. In the case that there aren't any elements in the combobox, you should have received a ArgumentOutOfRangeException instead.
Upvotes: 5