PriceCheaperton
PriceCheaperton

Reputation: 5349

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?

Upvotes: 0

Views: 3881

Answers (2)

user1448816
user1448816

Reputation:

    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 e.g

Upvotes: 2

Meysam Tolouee
Meysam Tolouee

Reputation: 579

Handle the TextBox_Validating for all textBoxes:

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;

Upvotes: 0

Related Questions