Use a recursive function, so that you go through the control and 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 her, inside a Form:
if (CamposVazios(this))
{
//Há algum campo vazio.
}
Suggestion:
In my case, I put one Exception
when the field is empty, because then I can inform the user which field is invalid, highlight the field or anything like that. 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 when calling the function:
try
{
CamposVazios(this);
//Processar / Gravar / etc...
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
"Among others" can hold a lot of things, man. Please specify which others are. Incidentally, your code makes very little sense.
– Jéf Bueno
That’s why I’m asking for help.
– Ronivaldo Roner
"Among others" can hold a lot of things, man. Please specify which others are
– Jéf Bueno
Among others would be text entries. Just follow the examples cited.
– Ronivaldo Roner
Combobox is not text input...
– Jéf Bueno
I will explain further. I have a layout, and I want to check that all fields are properly filled.
– Ronivaldo Roner
Sorry, you are correct. Anyway need to get the value of the selected item in it.
– Ronivaldo Roner
Okay, young man. That’s right. What I want to know is, what controls do you intend to validate in this method? Just
TextBoxes
andComboBoxes
?– Jéf Bueno
I have 3 elements I need to check, Combobox, Textbox and Maskedtextbox.
– Ronivaldo Roner
Right now!!!!!!!
– Jéf Bueno
Sorry, beginner here, do not want to put a conditional for each element the code would be too big, if there is another way to do thank you.
– Ronivaldo Roner
Unfortunately I was not able to solve, I found a solution that is to check the object passed to the database, so I will do so and continue studying the options presented until I understand 100% what happens.
– Ronivaldo Roner