Reputation: 291
I have created a ComboBox with three values. I wanted that a message box opens when no item is selected so I tried this:
if (comboBox1.SelectedItem == null)
{
MessageBox.Show("Please select a value");
return;
}
That works fine but only if I click into the field in the combobox. When I dont touch it, the program will start without message box. Whats wrong?
Upvotes: 12
Views: 94306
Reputation: 59
try this is the :
if ((comboBox.SelectedValue == null) || string.IsNullOrEmpty(comboBox.Text))
{
//message no items selected
}
Upvotes: 0
Reputation: 1
A ComboBox displays a text box combined with a ListBox, which enables the user to select items from the list or enter a new value. Conditionally testing SelectedItem or SelectedIndex will not handle the case of the user entering a new value from another input device like a keyboard. Use string.IsNullOrEmpty(comboBox1.Text) to handle all input/selection cases.
Upvotes: 0
Reputation: 536
Check the selected index value of dropdown equals -1
if (Comboboxid.SelectedIndex == -1){
MessageBox.Show("Your message.");
}
Upvotes: 2
Reputation: 736
Ithink this is the one :
if(comboBox.SelectedItems==null) //or if(comboBox.SelectedItems==-1)
{
//show no item was selected from comboBox
}
or
if(comboBox.SelectedItems.Count==0)
{
//message no items selected
}
Upvotes: 0
Reputation: 1240
Use
if (comboBox1.SelectedIndex == -1)
{
MessageBox.Show("Please select a value");
return;
}
Note: SelectedIndex will be set to -1 when SelectedValue is blank ONLY when FormattingEnabled is true. See here.
Upvotes: 3
Reputation: 548
The code should work. Although I will also set SelectedIndex as well......
if (this.comboBox1.SelectedItem == null || this.comboBox1.SelectedIndex == -1)
you mean "When I dont touch it, the program will start without message box. Whats wrong?" is there any code related with "touch it"
Upvotes: 1
Reputation: 1643
if (string.IsNullOrEmpty(comboBox1.Text))
or if (comboBox1.SelectedIndex == -1)
Upvotes: 24