0

I created a form with multiple panel over it and I use panel control to display relevant information. Third panel have 20 text boxes and I want to check whether all the details are filled. So I simply used this code below.

private void Calculatebutton_Click(object sender, EventArgs e)
{
    foreach(Control c in Controls)
    {
        if(c is TextBox)
        {
            Console.Beep();
            if (!String.IsNullOrWhiteSpace(textbox.Text) &&
                        !String.IsNullOrEmpty(textbox.Text))
                {
                    SaveToDatabaseButton.Enabled = true;
                }
        }
    }
  }

The problem is that the condition in the if statement is getting false, I cannot hear any beep sound or the other button enabled. if I changed from "c is TextBox" to "c is Panel" i can hear the beep sound for three times. I also tried the code like this

if(c is TextBox)
{
    c.Text = " ";
}

But nothing works. Please help me to overcome this problem. Thanks in advance.

Miss Chanandler Bong
  • 4,081
  • 10
  • 26
  • 36
Aaksh
  • 1
  • 1
  • Note that `Controls` here means `this.Controls` which returns _only_ the controls that are placed _directly_ on the form. Any controls that are placed in a child container (like a Panel or a GroupBox) are not included. Check the linked question to see how you can iterate all controls. – 41686d6564 stands w. Palestine Apr 14 '20 at 17:21
  • Please try to call `.Trim` method on your text, before checking it with `String.IsNullOrEmpty`. – Arsen Khachaturyan Apr 14 '20 at 18:41
  • Yes it worked. When i called the child container. Thanks . – Aaksh Apr 15 '20 at 08:47

1 Answers1

0

I tested your code and it entered the beep just fine, consider Ahmed's comments about the text boxes being in another container or form.

Not related to your question directly but, the logic of when to enable the button is incorrect as far as I can tell, because only one of the text boxes being not empty will suffice to enable the button to save to database, I assume you want all text boxes not empty for that to happen.

I would suggest something like this if that's the case:

private void Calculatebutton_Click(object sender, EventArgs e)
{
    var isThereEmptyTextBox = false;
    foreach(Control c in Controls)
    {
        if(c is TextBox)
        {
            Console.Beep();
            if (!String.IsNullOrWhiteSpace(textbox.Text) &&
                        !String.IsNullOrEmpty(textbox.Text))
                {
                    isThereEmptyTextBox = true;
                }
        }
    }
    SaveToDatabaseButton.Enabled = !isThereEmptyTextBox;
  }

As soon as just one text box is empty that flag will be set to true and will stay that way whether more empty text boxes appear or not, then you use that flag to enable/disable the button.

Raul Marquez
  • 948
  • 1
  • 17
  • 27