Check for combo box value

I created a ComboBox with three values. I wanted the message box to open when no item was selected, so I tried this:

if (comboBox1.SelectedItem == null) { MessageBox.Show("Please select a value"); return; } 

This works fine, but only if I click in the box in the combo box. When I do not touch it, the program will start without a message box. What's wrong?

+6
source share
5 answers

if (string.IsNullOrEmpty(comboBox1.Text)) or if (comboBox1.SelectedIndex == -1)

+11
source

Use

 if (comboBox1.SelectedIndex == -1) { MessageBox.Show("Please select a value"); return; } 

Note: SelectedIndex will be set to -1 if SelectedValue is empty ONLY when FormattingEnabled is true. See here .

+2
source

I think this is one thing:

  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 } 
+1
source

The code should work. Although I will also install SelectedIndex ...

 if (this.comboBox1.SelectedItem == null || this.comboBox1.SelectedIndex == -1) 

you mean: "When I do not touch it, the program will start without a message box. What happened?" is there any code related to "touch it"

+1
source

Check the selected outgoing value index value -1

 if (Comboboxid.SelectedIndex == -1){ MessageBox.Show("Your message."); } 
+1
source

Source: https://habr.com/ru/post/977809/


All Articles