MarcIT MarcIT - 14 days ago 5
C# Question

ignore hidden empty textboxes

Is there another way to ignore empty textboxes other than using if?
I have a form witch has many textboxes, some of them are filled by the db others by the user.
but when the user doesn´t fill one the app crashes.
i used this code to resolve:

if (larg.Text == string.Empty)
{
MessageBox.Show("info missing", "Warning");
return;
}
else if (this.alt.Text == string.Empty)
{
MessageBox.Show("Info Missing", "Warning");
return;


But what happens is, there are some textboxes witch are hidden and only appear depending on the value selected on the first form.
but i cant apply the if statment if the user picks an option witch displays only some of the textboxes.
When the user tries to submit the answer he gets the message that info is missing and the textbox is not even there.

The best solution i found is:

if (larg.Text == string.Empty)
{
if (larg.Hidden == False)
{
MessageBox.Show("info missing", "Warning");
return;
}
}


But i get erros in the line
if (larg.Hidden == False)


I hope i explained correctly.

Thanks for the suport.

I changed the code to:

foreach (Control c in Controls)
{
if (c is TextBox && larg.Visible && string.IsNullOrEmpty(c.Text))
{
MessageBox.Show($"TextBox {c.Name} is empty");
}
else if (c is TextBox && alt.Visible && string.IsNullOrEmpty(c.Text))
{
MessageBox.Show($"TextBox {c.Name} is empty");
}


but now i get errors if the textbox is empty.

Thanks for the help.

Answer

Have you thought of using a foreach of the form's controls instead? Something like:

        foreach (Control c in Controls)
        {
            if (c is TextBox && c.Visible && string.IsNullOrEmpty(c.Text))
            {
                MessageBox.Show($"TextBox {c.Name} is empty");
            }
        }
Comments