First of all, if you have 10 text boxes, it's already a good reason to avoid adding them using the Designer. Designer often means boring unproductive manual work which could be done in code much faster with much better quality, especially in terms of maintenance. If you do that, you problem would be reduced to:
TextBox[] textBoxes = new TextBox[textBoxCount];
foreach (TextBox textBox in textBoxes) { }
There is more "clever" and complex way which would work even if you don't have an array or other collections with your text boxes: you can create a loop based on
Control.Controls
, iterate some top control (Form, for example) through parent, and identify text boxes using:
void ProcessTextBoxes(Control parent) {
foreach(Control child in parent.Controls) {
TextBox textBox = child as TextBox;
if (textBox != null)
ProcessTextBox(textBox);
else
ProcessTextBoxes(parent);
}
}
You can do it all, but why? Not creating them with Designer is much easier and better for maintenance.
Finally, I am not that you need to check the text boxes for empty text at all. Maybe you need to handle the event
TextBox.TextChanged
to detect that the user ever changed the text. This is how some command like "Save" gets enabled. Also, you can check up the property
TextBox.Modified
. These methods can help you to handle the situation when the user entered the valid empty text. Please see:
http://msdn.microsoft.com/en-us/library/system.windows.forms.textboxbase.modified.aspx[
^],
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.textchanged.aspx[
^].
Even if you really need to check up the text values, in more general cases you need to
validate the values; an validation can be more complex then a check for emptiness. (By the way, chances are, you need to use
string.Trim
before this check. The validation is the regular holistic concept you should better get familiar with:
http://msdn.microsoft.com/en-us/library/ms229603.aspx[
^].
Good luck,
—SA