It is impossible to have a null check box, if it is added to some control of your UI. As it can be seen from your code, you are trying to check up the property
System.Window.Forms.TextBox.Text
, but this text is also never null, so all you need is to check it by comparison with
string.Empty
(which is of course not null, just empty string!).
Your code lacks
recursion. The problem is: some of the text boxes can be placed not directly on form, but on some other controls (panels). Actually, it's recommended to put everything on some hierarchy of panels and use docking. As a matter of thumb rule, never use manual placement.
To take it into account, your code should be something like that:
static TextBox FindEmptyTextBox(Control parent) {
TextBox textBox = parent as TextBox;
if (textBox != null) {
it (textBox.Text == string.Empty)
return textBox;
} else
foreach(Control child in parent.Controls) {
TextBox childTextBox = FindEmptyTextBox(child);
if (childTextBox != null)
return childTextBox;
}
return null;
}
This code will find the first empty text box encountered, hierarchically. It it returns null, there are no text boxed parented by a control, or they are all non-empty. If you apply this method to a form, it will find the first encountered text box on this form, hierarchically. Having the reference to a found control can be important, as you can focus on it and tell the user to input text in it (instead of ugly suggestion to the user to find all of them).
—SA