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

本文关键字:文本 验证 winforms 使用 | 更新日期: 2023-09-27 18:03:57

下面有一些代码:

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);

我如何验证空文本框,以确保文本框总是填充?

I have try:

if (string.IsNullOrEmpty(txtCompany.Text))
{
      //do work here
}
else
{
}

然而,我不知道我怎么能分配这样的所有文本框?以一种更简洁的方式限制我必须编写的代码行数?

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

    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方法,例如

处理所有textbox的textbox_valididating:

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;