c# Windows form application error on comboBox
I am new to c# windows form app. Here is my question: I created a comboBox in a form, and add items to this comboBox as below:
foreach (string name in seqNames)
{
comboBox.items.add(name);
}
and later check if any comboBox item is selected by
if (comboBox.selectedItem.toString().length > 0)
{
blabla;
}
but when I run it, without select any item in this combo box, I got an error : "Object referenc开发者_JS百科e not set to an instance of an object".
Anyone help me out? Please..... Thanks in advance.
If you make a reference to comboBox.SelectedItem
and no item is selected, then the selected item is null
and you can't do null.ToString()
.
Instead try testing the selected item like this:
if (comboBox.SelectedItem != null)
{
blabla;
}
SelectedItem
is returning null (i.e., no item is selected), and attempting to call a method on null
will result in an exception. Andrew has already noted this (+1 Andrew), but I thought I would add that you may benefit from setting the DropDownStyle
property to ComboBoxStyle.DropDownList
.
If you don't want your users typing into it and you always want some item selected this is a better approach, and in that case you can count on SelectedItem
never being null (assuming items cannot be removed from the ComboBox
and you always initialize it with at least one item.)
精彩评论