How to find out if a ComboBox contains any items?

14,104

Solution 1

Double click on your button in the Form and insert this code inside the click event handler : `

        //this code should work
        if (comboBox1.Items.Count == 0)
        {
            MessageBox.Show("Your combo is empty");
        }

   `

Solution 2

I use

if (comboBox1.SelectedItem!=null)
{
    MessageBox.Show("Combo is not empty");
}

to determine if something is selected

And I use this to determine if the comboBox has any items.

if (comboBox1.Items.Count > 0)
{
    MessageBox.Show("Your combo is not empty");
}

Solution 3

If no item selected/Present, then SelectedIndex property returns -1.

  if (combobox1.SelectedIndex == -1) 
    //no item selected/present

Solution 4

Well, I am sure if you check out ComboBox class on MSDN: http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox_properties, it'd benefit you.

Also, personally I wouldn't tend to use selectedIndex or selectedItem property, as there can be a case where item collection is not empty but none of any items are actually selected. Use items.count is a better way to decide if item collection is empty or not.

Share:
14,104
user1421743
Author by

user1421743

Updated on June 05, 2022

Comments

  • user1421743
    user1421743 almost 2 years

    I have simple WinForms application in C# which has two controls: combobox1 and button. I would like to find out if there are any items in combobox1.

    I have tried this, but it only tells me if there is a selected item:

    if (combobox1.Text != ""))
    {
        MessageBox.Show("Combo is not empty");
    }
    
  • Rajesh Subramanian
    Rajesh Subramanian almost 12 years
    then combobox1.Items.Count could help you
  • Nadir Sampaoli
    Nadir Sampaoli almost 12 years
    shouldn't it be combobox1.Items.Count == 0? I don't think you can have a negative count.