【问题标题】:How to find out if a ComboBox contains any items?如何找出 ComboBox 是否包含任何项目?
【发布时间】:2012-06-11 11:24:35
【问题描述】:

我有一个简单的 C# WinForms 应用程序,它有两个控件:combobox1button。我想看看combobox1里有没有东西。

我试过这个,但它只告诉我是否有选定的项目:

if (combobox1.Text != ""))
{
    MessageBox.Show("Combo is not empty");
}

【问题讨论】:

    标签: c# winforms combobox


    【解决方案1】:

    双击表单中的按钮并将此代码插入到单击事件处理程序中:`

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

    【讨论】:

    • 不应该是combobox1.Items.Count == 0吗?我认为你不能有负数。
    【解决方案2】:

    我用

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

    确定是否选择了某物

    我用它来确定组合框是否有任何项目。

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

    【讨论】:

      【解决方案3】:

      如果没有选择/存在项目,则 SelectedIndex 属性返回 -1。

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

      【讨论】:

      • 那么 combobox1.Items.Count 可以帮助你
      【解决方案4】:

      好吧,我相信如果您查看 MSDN 上的 ComboBox 类:http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox_properties,它会对您有所帮助。

      另外,我个人不倾向于使用selectedIndexselectedItem 属性,因为可能存在项目集合不为空但实际上没有任何项目被选中的情况。使用items.count 是确定项目集合是否为空的更好方法。

      【讨论】:

        【解决方案5】:
        if (ComboBox.Items!=null && ComboBox.Items.Count>0)
        {
          //have some item 
        }
        

        如果你需要知道有多少项目有使用

        string Count = ComboBox.Items.Count;
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-08-02
          • 2020-06-24
          • 2023-03-27
          • 1970-01-01
          • 2016-08-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多