【问题标题】:How to make if statement that checks if multple listBoxes are empty or not?如何制作 if 语句来检查多个列表框是否为空?
【发布时间】:2015-06-16 04:29:00
【问题描述】:

如何创建一个 if 语句来询问多个 listBox 是否为空?

这就是我目前所拥有的......是否可以将它组合成一个 if 语句?

    if (listBoxEmails.Items.Count < 1)
    {
     //Perform action
    }

    if (listBoxWebsites.Items.Count < 1)
    {
    //Perform action
    }

    if (listBoxComments.Items.Count < 1)
    {
       //Perform action
    }

【问题讨论】:

  • 我想检查每个是否为空。所以我希望程序检查的逻辑是 listBox1 是否为空,或者 listBox2 是否为空,或者 listBox3 是否为空。我尝试使用 ||为此,但它不起作用。
  • @EdwinTorres 你说的空是什么意思?列表框文本为空或项目数为零,
  • 更新了我的答案。希望对您有所帮助,
  • 是否所有的执行动作都相同,那么只有整合所有三个调用并执行动作,否则你必须单独处理它们

标签: c# winforms if-statement listbox


【解决方案1】:

如果您尝试从表单上的所有列表框中获取计数,您可以这样做:

if (Controls.OfType<ListBox>().Any(z => z.Items.Count < 1))
{
    // Do Something
}

神奇之处在于,如果您在表单上删除或添加更多列表框,则无需更改任何代码。如果你想获取特定的列表框,你可以将所有列表框的Tag 属性设置为CountedListBox 之类的东西,然后执行以下操作:

if (Controls.OfType<ListBox>().Any(z => z.Items.Count < 1 && ((string)z.Tag == "CountedListBox")))
{
    // Do something
}

【讨论】:

    【解决方案2】:

    您可以在某些集合中包含列表框,如果列表中的任何一个是否为空,您可以使用 linq 在一个语句中找到。像这样的东西。当然,列表框集合可以有不同的方法。

        private void ValidateListBoxes()
        {
            List<ListBox> listBoxes = new List<ListBox>();
            listBoxes.Add(listBoxEmails);
            listBoxes.Add(listBoxWebsites);
            listBoxes.Add(listBoxComments);
    
            bool isContainingEmptyList = listBoxes.Any(l => l.Items.Count < 1 || l.Items.Count==0);
        }
    

    【讨论】:

      【解决方案3】:
      if (listBoxEmails.Items.Count >= 0 && listBoxWebsites.Items.Count >= 0 && 
      
          listBoxComments.Items.Count >= 0)
          {
          //perform action
      
          }
      

      【讨论】:

      • 谢谢!最简单的解决方案,这正是我所需要的。我所做的只是用 || 替换 &&它奏效了:)
      【解决方案4】:

      这是我能想到的最简单的解决方案,

      if (listBoxEmails.Items.Any() && listBoxWebsites.Items.Any() && listBoxComments.Items.Any())
      {
          // Do something here,
       }
      

      【讨论】:

      • 先阅读OP的要求。谢谢
      • 它说没有.Any的定义?
      • 你需要为Linq添加命名空间,
      • 我使用 System.Linq 添加,但仍然收到此错误:错误 5 'System.Windows.Forms.ListBox.ObjectCollection' 不包含 'Any' 的定义并且没有扩展方法 'Any'可以找到接受“System.Windows.Forms.ListBox.ObjectCollection”类型的第一个参数(您是否缺少 using 指令或程序集引用?
      • 首先将您的项目转换为 ListItem 然后您可以执行任何 linq 操作。例如lbxCustomers.Items.Cast().Any()
      【解决方案5】:

      这是在 WPF 还是 WinForms 中?你可以这样做:

          var performAction = (!listBoxEmails.Items.IsEmpty | !listBoxWebsites.Items.IsEmpty | !listBoxComments.Items.IsEmpty);
          if (performAction)
          {
      
          }
      

      【讨论】:

      • Winforms。我在“.IsEmpty”部分使用您的代码时出错
      • 好吧,我没有意识到你在使用 WinForms。我会将标签添加到您的问题中
      猜你喜欢
      • 2020-04-27
      • 1970-01-01
      • 2018-03-16
      • 2022-11-17
      • 2021-07-06
      • 1970-01-01
      • 2021-10-25
      • 1970-01-01
      • 2021-12-18
      相关资源
      最近更新 更多