uzi42tmp
uzi42tmp

Reputation: 291

Check if combobox value is empty

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

Answers (7)

Ammar Abdul Wadood
Ammar Abdul Wadood

Reputation: 59

try this is the :

  if ((comboBox.SelectedValue == null) || string.IsNullOrEmpty(comboBox.Text))
                        {
    
    //message no items selected 
                    }

Upvotes: 0

John-Michael Bishop
John-Michael Bishop

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

Manish sharma
Manish sharma

Reputation: 536

Check the selected index value of dropdown equals -1

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

Upvotes: 2

AVIK DUTTA
AVIK DUTTA

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

Octane
Octane

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

liuzhidong
liuzhidong

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

free4ride
free4ride

Reputation: 1643

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

Upvotes: 24

Related Questions