How to find out if combobox have some items inside?

I have simple winforms application in C# which has two controls: combobox1 and button. Of course, a ComboBox and Button respectively. 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");
}

Answers


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");
        }

   `

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");
}

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

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

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.


if (ComboBox.Items!=null && ComboBox.Items.Count>0)
{
  //have some item 
}

and if you need to know how many item have Use

string Count = ComboBox.Items.Count;

Need Your Help

Rails3 finding date objects in calendar month

datetime ruby-on-rails-3.2

Most Date methods will do a calculation based on the present time or date and jump to that date in X number of months. However if one wants to extract all the objects that have a date within a solar