How to find out if a ComboBox contains any items?
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.
user1421743
Updated on June 05, 2022Comments
-
user1421743 almost 2 years
I have simple WinForms application in C# which has two controls:
combobox1
andbutton
. I would like to find out if there are any items incombobox1
.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 almost 12 yearsthen combobox1.Items.Count could help you
-
Nadir Sampaoli almost 12 yearsshouldn't it be
combobox1.Items.Count == 0
? I don't think you can have a negative count.