使用Linq循环遍历所有控件只能获得第一个控件

时间:2016-06-01 14:08:31

标签: c# linq

我有一个包含5个文本框和一个按钮的表单,我想检查所有这些文本框是否为空或空用户输入。 使用这个简单的方法:

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (verifyUI() == true)
                MessageBox.Show("user input for all textboxes was correct!");
            else
                MessageBox.Show("user input for all textboxes was missing!");
        }

        private bool verifyUI()
        {
            bool userInputOk = false;
            foreach (Control cTxt in Controls.OfType<TextBox>())
            {
                if (string.IsNullOrWhiteSpace(cTxt.Text) || cTxt.Text == "")
                {
                    userInputOk = false;
                }
                else
                {
                    userInputOk = true;
                }
            }
            return userInputOk;
        }
    }

当我在文本框1中输入值时,该方法仅检查第一个文本框并返回true,并忽略所有其他文本框。

我确信我正在使用的方法的逻辑有问题。

6 个答案:

答案 0 :(得分:8)

您似乎想知道任何输入是否错误(或所有输入是否正确):

  private bool verifyUI() {
    return !Controls
      .OfType<TextBox>() 
      .Any(cTxt => string.IsNullOrWhiteSpace(cTxt.Text));
  }

或(等效All()实施)

  private bool verifyUI() {
    return Controls
      .OfType<TextBox>() 
      .All(cTxt => !string.IsNullOrWhiteSpace(cTxt.Text));
  }

在您当前的代码中,您经常重写 userInputOk,因此返回 last

答案 1 :(得分:2)

最简单的方法是使用(Rs.|[$£€¥₹])?\s*(\d{1,3}(?:[, ]?\d{1,3})?(?:.\d+)?)(?(1)|\s*(kr\.?|Kč|INR|€)) 方法:

All

您也可以反转逻辑并使用{​​{1}}方法。在这种情况下,我更喜欢private bool verifyUI() { return Controls.OfType<TextBox>().All(tb => !string.IsNullOrWhiteSpace(tb.Text)); } ,因为它更好地传达了意图,并使下一个人的逻辑更清晰。

答案 2 :(得分:2)

我认为只是为了检查是否没有填充任何文本框。以下代码就足够了。

        private bool verifyUI()
        {
            bool alluserInputsOk = true;
            foreach (Control cTxt in Controls.OfType<TextBox>())
            {
                if (string.IsNullOrWhiteSpace(cTxt.Text))
                {
                    userInputOk = false;
                    break;
                }                   
            }
            return userInputOk;
        }

或者您可以在列表中使用.any()方法

答案 3 :(得分:1)

您的代码实际上只是检查列表中的最后一个控件是否为空,因为您的迭代结束了。

答案 4 :(得分:0)

您的代码仅检查找到的最后一个文本框。请尝试使用此All()语句:

bool userInputOk = Controls.OfType<TextBox>()
                           .All(tb => !string.IsNullOrWhiteSpace(tb.Text));

注意 string.IsNullOrWhiteSpace() true string.Empty也是string.Empty。因此,您不需要对{{1}}进行额外检查。

答案 5 :(得分:0)

实际上,它可能会循环所有控件,但只返回 last 的结果,因为您将userInputOk 的值设置为为true如果控件有有效文本。因此,最终结果是 last 控件的结果。现在,textBox1可能是集合中的 last 控件,具体取决于它们的添加方式。您可以删除else块,如果控件的值无效,则会仅标记userInputOk ,或使用Linq:

 bool userInputOk = 
          !Controls.OfType<TextBox>()
                   .Any(cTxt => string.IsNullOrWhiteSpace(cTxt.Text))