【问题标题】:Validating multiple textboxes using errorprovider使用 errorprovider 验证多个文本框
【发布时间】:2012-08-26 11:43:45
【问题描述】:

我有 10 个文本框,现在我想在单击按钮时检查它们是否为空。 我的代码是:

 if (TextBox1.Text == "")
 {
    errorProvider1.SetError(TextBox1, "Please fill the required field");
 }

有什么方法可以一次检查所有的文本框,而不是为每个人写?

【问题讨论】:

  • 几乎可以肯定是 Windows 窗体,而不是 asp.net。

标签: c# winforms


【解决方案1】:

是的,有。

首先,您需要以序列的形式获取所有文本框,例如:

var boxes = Controls.OfType<TextBox>(); 

然后,您可以遍历它们,并相应地设置错误:

foreach (var box in boxes)
{
    if (string.IsNullOrWhiteSpace(box.Text))
    {
        errorProvider1.SetError(box, "Please fill the required field");
    }
}

我建议使用string.IsNullOrWhiteSpace 而不是x == "" 或+string.IsNullOrEmpty 来将填充有空格、制表符等的文本框标记为错误。

【讨论】:

    【解决方案2】:

    可能不是最佳解决方案,但这也应该可行

        public Form1()
        {
           InitializeComponent();
           textBox1.Validated += new EventHandler(textBox_Validated);
           textBox2.Validated += new EventHandler(textBox_Validated);
           textBox3.Validated += new EventHandler(textBox_Validated);
           ...
           textBox10.Validated += new EventHandler(textBox_Validated);
        }
    
        private void button1_Click(object sender, EventArgs e)
        {
            this.ValidateChildren();
        }
    
        public void textBox_Validated(object sender, EventArgs e)
        { 
            var tb = (TextBox)sender;
            if(string.IsNullOrEmpty(tb.Text))
            {
                errorProvider1.SetError(tb, "error");
            }
        }
    

    【讨论】:

      【解决方案3】:

      编辑:

      var controls = new [] { tx1, tx2. ...., txt10 };
      foreach(var control in controls.Where(e => String.IsNullOrEmpty(e.Text))
      {
          errorProvider1.SetError(control, "Please fill the required field");
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-06-23
        • 1970-01-01
        • 2012-02-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多