Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Can I Get The Button Controls in Windows Form - Panel

Tags:

c#

winforms

Get All the Buttons In A Form including the buttons in the panel of the same form..

like image 308
Ganguly_S Avatar asked Jun 21 '11 06:06

Ganguly_S


3 Answers

 List<Control> list = new List<Control>();

            GetAllControl(this, list);

            foreach (Control control in list)
            {
                if (control.GetType() == typeof(Button))
                {
                    //all btn
                }
            }

        private void GetAllControl(Control c , List<Control> list)
        {
            foreach (Control control in c.Controls)
            {
                list.Add(control);

                if (control.GetType() == typeof(Panel))
                    GetAllControl(control , list);
            }
        }
like image 97
hashi Avatar answered Nov 20 '22 13:11

hashi


Here is what I have done, I wrote a simple function, when I click a Button, I Select Only the Panel Control and pass it to a function for further loop through the control on that panel.

private void cmdfind_Click(object sender, EventArgs e)
    {
        try
        {
            foreach (Control control in this.Controls)
            {
                if (control.GetType() == typeof(Panel))
                    //AddToList((Panel)control); //this function pass the panel object so further processing can be done 
            }                         
        }
        catch (System.Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

    }
like image 36
DareDevil Avatar answered Nov 20 '22 15:11

DareDevil


try this

foreach (var control in this.Controls)
{
   if (control.GetType()== typeof(Button))
   {

       //do stuff with control in form
   }

   else if (control.GetType() == typeof(Panel))
   {
       var panel = control as Panel;
       foreach (var pan in panel.Controls)
       {
           if (pan.GetType() == typeof(Button))
           {

                //do stuff with control in panel
           }
        }
    }              

} 
like image 26
Javed Akram Avatar answered Nov 20 '22 15:11

Javed Akram