如何在Windows窗体面板中获取按钮控件

本文关键字:获取 按钮 控件 体面 Windows 窗体 | 更新日期: 2023-09-27 17:59:53

获取表单中的所有按钮,包括相同形式的面板中的按钮.

如何在Windows窗体面板中获取按钮控件

 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);
            }
        }

以下是我所做的,我写了一个简单的函数,当我点击一个按钮时,我只选择面板控件,并将其传递给一个函数,以便在该面板上的控件中进一步循环。

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);
        }
    }

尝试这个

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
           }
        }
    }              
}