cyberpunkalpaca
cyberpunkalpaca

Reputation: 11

Loop through all GroupBoxes on Windows Form

I'm currently working on a personal project using C# and ADO.NET in VS2015 to make a basic windows form that interfaces with a database.

I am currently writing a series of Clear routines that will reset the various form elements. All form controls are housed within GroupBoxes. I am trying to determine the best way to loop through the all of the GroupBoxes, so I can then loop through each control and clear it. For now I am only attempting to clear TextBoxes.

Here is what I've got for code:

public void ClearTextBoxes(Control control)
    {
        foreach (GroupBox groupBox in control.Controls)
        {
            foreach (Control con in groupBox.Controls)
            {
                if (con is TextBox)
                {
                    ((TextBox)con).Clear();
                }
            }
        }    
    }

Currently, I receive an error on the second line that states: An unhandled exception of type 'System.InvalidCastException'

If anyone could help me figure my way through this it would be greatly appreciated!

Upvotes: 1

Views: 709

Answers (1)

cyberpunkalpaca
cyberpunkalpaca

Reputation: 11

I determined my problem was overlooking that GroupBoxes have children. By considering the child controls in my subroutine I was able to resolve the issue. After fixing the issue and doing a little cleanup here is what my code looks like:

public void ClearTextBoxes(Control control)
    {
        foreach (Control con in control.Controls)
        {
            TextBox box = con as TextBox;
            box?.Clear();

            if (con.HasChildren)
            {
                ClearTextBoxes(con);
            }
        }
    }

Upvotes: 0

Related Questions