What would be the most efficient way to check that a series of text boxes are completed prior to allowing the execution of code since executing the code without values being completed errors out the program.

Recommended Answers

All 5 Replies

fairly open question there, depends so much on how and what ..

By complete, do you mean not an empty string, or do they need to meet some criteria?

The most efficient way would be to use the hard coded names of the text boxes

if ((!string.IsNullOrEmpty(textEdit1.Text)) && (!string.IsNullOrEmpty(textEdit2.Text)) && (!string.IsNullOrEmpty(textEdit3.Text))
{
  //do work
}
{
  //else error
}

However you will likely want to flash an informative error message or focus the text box that has not been filled in. In this case you will want to iterate the controls in the parent container and check their value. It is slightly slower but far more maintainable and you are less likely to have a bug.

A more maintainable way:

private void button1_Click(object sender, EventArgs e)
    {
      errorProvider1.Clear();
      TextBox firstBoxWithError = null;

      foreach (Control ctrl in this.Controls)
      {
        if (ctrl is TextBox)
        {
          TextBox box = ((TextBox)ctrl);
          if (string.IsNullOrEmpty(box.Text))
          {
            errorProvider1.SetError(box, "Please fill in the text box.");
            if (firstBoxWithError == null)
              firstBoxWithError = box;
          }
        }
      }

      if (firstBoxWithError != null) //you have at least one bad box
      {
        firstBoxWithError.Focus(); //focus the box before showing the error, makes it more intuitive
        MessageBox.Show("Please finish filling in the data.");
        firstBoxWithError.Focus(); //sometimes users double click error box and lose focus
        return;
      }
      else
      {
        //do the important stuff
      }
    }

By complete, do you mean not an empty string, or do they need to meet some criteria?

I mean not an empty string.

then do 1 simple if statement.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.