Use a recursive function, so you can take control of your children:
public static bool CamposVazios(Control _ctrl)
{
foreach (Control c in _ctrl.Controls)
{
if (c is TextBox)
{
if (String.IsNullOrEmpty(((TextBox)c).Text))
return true;
}
else if (c is ComboBox)
{
if (((ComboBox)c).SelectedValue == null)
return true;
}
else if (c.HasChildren)
{
if (CamposVazios(c))
return true;
}
}
return false;
}
To call it, inside a Form:
if (CamposVazios(this))
{
//Há algum campo vazio.
}
Suggestion:
In my case, I put a Exception
when the field is blank, because then I can tell the user which field is invalid, highlight the field or anything. Ex:
public static void CamposVazios(Control _ctrl)
{
foreach (Control c in _ctrl.Controls)
{
if (c.HasChildren)
{
CamposVazios(c);
}
else if (c is TextBox)
{
if (String.IsNullOrEmpty(((TextBox)c).Text))
{
throw new Exception("Campo "+ c.Name + " está vazio");
}
}
else if (c is ComboBox)
{
if (((ComboBox)c).SelectedValue == null)
{
throw new Exception("Campo "+ c.Name + " está vazio");
}
}
}
}
and at the time of calling the function:
try
{
CamposVazios(this);
//Processar / Gravar / etc...
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}