我在 C# 中有一个简单的 WinForms 应用程序,它有两个控件:combobox1
和button
. 我想知道 中是否有任何项目combobox1
。
我试过这个,但它只告诉我是否有一个选定的项目:
if (combobox1.Text != ""))
{
MessageBox.Show("Combo is not empty");
}
双击表单中的按钮并将此代码插入到单击事件处理程序中:`
//this code should work
if (comboBox1.Items.Count == 0)
{
MessageBox.Show("Your combo is empty");
}
`
我用
if (comboBox1.SelectedItem!=null)
{
MessageBox.Show("Combo is not empty");
}
确定是否选择了某物
我用它来确定组合框是否有任何项目。
if (comboBox1.Items.Count > 0)
{
MessageBox.Show("Your combo is not empty");
}
如果没有选择/存在项目,则 SelectedIndex 属性返回 -1。
if (combobox1.SelectedIndex == -1)
//no item selected/present
好吧,我敢肯定,如果您查看 MSDN 上的 ComboBox 类:http: //msdn.microsoft.com/en-us/library/system.windows.forms.combobox_properties,它会对您有所帮助。
此外,我个人不会倾向于使用selectedIndex
orselectedItem
属性,因为可能存在项目集合不为空但实际上没有选择任何项目的情况。使用items.count
是确定项目集合是否为空的更好方法。
if (ComboBox.Items!=null && ComboBox.Items.Count>0)
{
//have some item
}
如果您需要知道有多少项目有使用
string Count = ComboBox.Items.Count;