使用C#验证winforms中的空文本框

时间:2014-05-18 09:28:57

标签: c# winforms validation isnullorempty

我有以下代码:

SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.Parameters.AddWithValue("@company", txtCompany.Text);
command.Parameters.AddWithValue("@server", txtServer.Text);
command.Parameters.AddWithValue("@username", txtUserName.Text);
command.Parameters.AddWithValue("@password", txtPassword.Text);

如何验证空文本框,确保文本框始终填充?

我试过了:

if (string.IsNullOrEmpty(txtCompany.Text))

{
      //do work here
}

else
{

}

但我不知道如何分配这样的所有文本框?以更清洁的方式限制我必须编写的代码行数?

2 个答案:

答案 0 :(得分:2)

    private bool ValidateTextBoxes()
    {
        try
        {
            string textBoxData = string.Empty;

            foreach (Control item in this.Controls)
            {
                if (item.GetType() == typeof(TextBox))
                {
                    textBoxData += item.Text;
                }
            }
            return (textBoxData != string.Empty);
        }
        catch { return false; }
    }

    if(ValidateTextBoxes())
    {
         // your code..
    }

在执行数据库操作之前,只需调用ValidateTextBoxes方法,例如

答案 1 :(得分:0)

处理所有textBoxes的TextBox_Validating:

public Form1()
{
    InitializeComponent();

    txtCompany.Validating += TextBox_Validating;
    txtServer.Validating  += TextBox_Validating;
    txtUserName.Validating  += TextBox_Validating;
    txtPassword.Validating  += TextBox_Validating;
}
private void TextBox_Validating(object sender, CancelEventArgs e)
{
    TextBox control = sender as TextBox;
    control.Focus();   
    e.Cancel = control.Text == string.Empty;
}

您也可以在执行命令之前添加此代码:

bool controlsAreValid = true;

foreach (Control control in this.Control)
{
   if (control is TextBox)
   {
      if (control.Text == string.Empty)
      {
          controlsAreValid = false;
          break;
      }
   }
}
if (!controlsAreValid)
     return;