Click here to Skip to main content
15,894,036 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
How to loop through all the controls regardless of them being on a panel or groupbox,...
Now i have something like this:
I added another class and in this class is the code:
 public void New(Form1 f1)
        {  
 foreach (Control c in f1.Controls)
            {

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

            }

How to fix this code, to get the controls inside panels, groupboxes and so on?
Posted

C#
foreach(Control ctrl in this.Controls)
{
    if(ctrl is TextBox)
        string str = ((TextBox)ctrl).Text;
    
    if(ctrl is ComboBox)
        string str = ((ComboBox) ctrl).SelectedItem.ToString();
    
    // and so on...
}

-KR
 
Share this answer
 
You are correct: the other responses here do not deal with Controls inside Container Controls, like Panel, and GroupBox, in the Form.

To find all the TextBoxes, and ComboBoxes, on the Form, no matter how "deeply" they are "nested" inside Container Controls, requires a recursive search.

In my response to a previous QA question I provided code for recursively building a collection of all Controls on a Form using the "stack-based" technique recommended by Eric Lippert: [^].

You can take that code and use it, like this:
C#
// requires Linq

// clear Text in all TextBoxes
foreach (TextBox theTextBox in (SpecialMethods.GetAllControls(this)).OfType<TextBox>().ToList())
{
    theTextBox.Clear();
}

// clear ComboBoxItems in all ComboBoxes
foreach (ComboBox theComboBox in (SpecialMethods.GetAllControls(this)).OfType<ComboBox>().ToList())
{
    theComboBox.Items.Clear();
}
 
Share this answer
 
v2
C#
foreach (Control objControl in this.Controls)
            {

                if (objControl.GetType() == typeof(TextBox))
                {
                    TextBox objTxt = (TextBox)objControl;
                    objTxt.Text = "";
                }
            }



Try others control with same way.
Thanks
 
Share this answer
 
Those two solutions do the same thing - only working for controls that are put directly on a form. If controls are inside groupbox or panel, it does nothing.
If i use this:
foreach (Control c in f1.groupBox1.Controls)
       {

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

       }

deletes controls inside groupBox1. But i don't want to write the code for every groupbox, panel,...
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900