check a series of text boxes prior to executing
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.
MJV
Junior Poster in Training
67 posts since Feb 2009
Reputation Points: 10
Solved Threads: 0
fairly open question there, depends so much on how and what ..
LizR
Posting Virtuoso
1,791 posts since Aug 2008
Reputation Points: 196
Solved Threads: 190
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
}
}
sknake
Industrious Poster
4,954 posts since Feb 2009
Reputation Points: 1,764
Solved Threads: 735
By complete, do you mean not an empty string, or do they need to meet some criteria?
I mean not an empty string.
MJV
Junior Poster in Training
67 posts since Feb 2009
Reputation Points: 10
Solved Threads: 0
then do 1 simple if statement.
LizR
Posting Virtuoso
1,791 posts since Aug 2008
Reputation Points: 196
Solved Threads: 190