0

我在下面有一些代码:

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
{

}

但是我不确定如何分配这样的所有文本框?以一种更简洁的方式限制我必须编写的代码行数?

4

2 回答 2

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

于 2014-05-18T09:50:51.237 回答
0

处理所有文本框的 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;
于 2014-05-18T09:35:18.707 回答