简体   繁体   English

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

[英]Validate empty text boxes in winforms using C#

I have some code below: 我在下面有一些代码:

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

How do i validate empty textboxes making sure that the textboxes are alway populated? 如何验证空文本框,确保文本框始终填充?

I have tried: 我努力了:

if (string.IsNullOrEmpty(txtCompany.Text))

{
      //do work here
}

else
{

}

However im not sure how i can assign ALL text boxes like this? 但是,我不知道如何分配这样的所有文本框? in a cleaner way which limits the number of lines of code i have to write? 以更清洁的方式限制我必须编写的代码行数?

    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..
    }

Just call the ValidateTextBoxes method before performing database operations eg 只需在执行数据库操作之前调用ValidateTextBoxes方法,例如

Handle the TextBox_Validating for all textBoxes: 处理所有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;
}

Also you can add this code before executing the command: 您也可以在执行命令之前添加此代码:

bool controlsAreValid = true;

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM