检查所有文本框不包含空格/空值

时间:2015-02-23 06:22:04

标签: c# string forms function

我有一个包含多个文本框的表单,我想循环遍历文本框,看看是否有任何文本框包含null或空格。如果他们这样做,那么我想要返回一个布尔值。

  

我得到的错误:       {"无法转换类型为&System;对象类型的对象。#System; Windows.Forms.Button'键入' System.Windows.Forms.TextBox'。"} {"无法投射   类型对象System.Windows.Forms.Button'输入   ' System.Windows.Forms.TextBox'"}

我的代码:

        private bool EmptyTextBox()
    {
        //returns false if all the text boxs contain strings otherwise it will set the messagebox then return true
        /*if (!Controls.Cast<TextBox>().Any(textBox => String.IsNullOrWhiteSpace(textBox.Text))) return false;
        MessageBox.Show("Please do not leave a textbox blank.");*/
        foreach (TextBox textBox in this.Controls)
        {
            if (string.IsNullOrWhiteSpace(textBox.Text))
            {
                MessageBox.Show("Please do not leave a textbox blank.");
                return false;

            }
        }
        return true;
    }

我想知道我做错了什么以及如何解决这个问题,谢谢。

4 个答案:

答案 0 :(得分:3)

this.Controls会返回所有类型的控件。 ButtonTextBoxComboBox等等。在foreach语句中,您将所有控件都转换为TextBox。这就是这个例外的原因。您只需要获得TextBox个控件。 您可以使用Enumerable.OfType<TResult>命名空间中的System.Linq

将您的代码更改为:

 foreach (TextBox textBox in this.Controls.OfType<TextBox>())
        {
            if (string.IsNullOrWhiteSpace(textBox.Text))
            {
                MessageBox.Show("Please do not leave a textbox blank.");
                return false;
            }
        }

或者如果你喜欢一个行代码:

private bool EmptyTextBox()
{
     bool result = this.Controls.OfType<TextBox>().Any(x => string.IsNullOrWhiteSpace(x.Text));

     if(result==true) MessageBox.Show("Please do not leave a textbox blank.");

     return !result;
}

答案 1 :(得分:1)

试试这个:

你几乎就在那里!

if (!Controls.OfType<TextBox>().Any(textBox => 
String.IsNullOrWhiteSpace(textBox.Text))) return false;

OfType - 仅返回您提供的类型的元素。

Cast-将尝试将所有元素转换为您提供的类型

答案 2 :(得分:0)

对每个文本框使用必填字段验证器总是比在后端检查它更好。它会在没有回复的情况下给出错误消息。

答案 3 :(得分:-1)

//SIMPLE WAY TO VALIDATE EMPTY SPACES
if (txtusername.Text.Contains(" "))
{
    MessageBox.Show("Invalid Username");
    txtusername.Clear();
    txtusername.Focus();
}
相关问题