I always end up creating a quick return statement above a code block if the simple condition of textbox null fields are found. Naturally, these tend to build up the more controls are added. Now I'm staring at this mess of code, and I'm looking for advice as to avoid this very common mistake in the future.
This is the spaghetti code of a small winform C# project that I'm sure will trigger more than a few people:
if (txtFirst.Text == "" || txtLast.Text == "" || txtGross.Text == "" ||
txtLessTNT.Text == "" || txtTCI.Text == "" || txtADDTI.Text == "" || txtGTI.Text == "" ||
txtLessTE.Text == "" || txtLessPPH.Text == "" || txtLessNTI.Text == "" || txtTD.Text == "" ||
txtTWCE.Text == "" || txtTWPE.Text == "" || txtTATW.Text == "" ||
txtFirst.Text == " " || txtLast.Text == " " || txtGross.Text == " " ||
txtLessTNT.Text == " " || txtTCI.Text == " " || txtADDTI.Text == " " || txtGTI.Text == " " ||
txtLessTE.Text == " " || txtLessPPH.Text == " " || txtLessNTI.Text == " " || txtTD.Text == " " ||
txtTWCE.Text == " " || txtTWPE.Text == " " || txtTATW.Text == " " || txtID.Text == "" ||
txtID.Text == " " || txtTIN.Text == "" || txtTIN.Text == " " || txtFrom.Text == " " || txtFrom.Text == "" || txtTo.Text == " " || txtTo.Text == "" || txtCTC.Text == " " || txtCTC.Text == "" || txtCTC.Text == " " || txtPOI.Text == "" || txtPOI.Text == " " || txtDOI.Text == "" || txtDOI.Text == " " || txtDOI.Text == "" || txtAMT.Text == " " || txtAMT.Text == ""
)
{
MessageBox.Show("Cannot enter null values!");
return;
}
Surely, there is an easier way to do this that allows the code to be modular and concise that permits the addition of new textbox controls. This happens more often than I'd like to admit and I wish to get rid of this habit once and for all.
Note that, I do have another solution, it's a linq block that iterates through ALL textbox controls in a given form. But what I'm looking for is as I mentioned, code that allows for selection of the controls involved.
TextBox
control, add your code there, and use thatNonNullTextBox
control class where you want this behavior instead of the built-in one. I'd have posted this as a complete solution in an answer, but I'm not sure what event you would want to put this logic in—when do you want to test that the contents are non-null? During validation? What is the purpose of this code? Also, note that this is pretty bad design. You should let the user enter whatever they want, and check it all when they try to submit the form. \$\endgroup\$