Search code examples
c#type-conversionuser-controlscontrols

How to convert a UserControl into control


I've created a program with a Panel, with a button I can add a UserControl in to the Panel. The UserControl contains only a ComboList

What I would like to do is to get all the UserControl in my Panel and get their value back. I tried this but my program does not detect any ComboBoxes, so the table is empty:

private void button_add_outil_Click(object sender, EventArgs e)
        {
            // Récupère tous les élèves présents
            List<string> eleve = new List<string>();

            foreach (Control ctrl in panel_eleve.Controls)
            {

                if (ctrl is ComboBox)
                {
                    ComboBox c = ctrl as ComboBox;
                    eleve.Add(c.SelectedText);
                }
            }

            addOutil add_outil_window = new addOutil(eleve);
            add_outil_window.ShowDialog();
        }

Does anyone know how to convert a UserControl into a Control at the same time? Thank you.


Solution

  • This is pseudo code (and I'm assuming your UserControl is a container) but, as mentioned in my comment, I think you'll need to do something like the following:

            // Récupère tous les élèves présents
            List<string> eleve = new List<string>();
    
            foreach (Control ctrl in panel_eleve.Controls)
            {
    
                if (ctrl is UserControl) // You may be able to be more specific with this type
                {
    
                       foreach (Control innerControl in ctrl.Controls )
                       {
                           if (innerControl is ComboBox)
                           {
                                ComboBox c = innerControl as ComboBox;
                                eleve.Add(c.SelectedText);
                           }
    
                       }
    
                }
            }
    
            addOutil add_outil_window = new addOutil(eleve);
            add_outil_window.ShowDialog();