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

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

List list = new List(); GetAllControl(this, list); foreach (Control control in list) { if (control.GetType() == typeof(Button)) { //all btn } } private void GetAllControl(Control c , List list) { foreach (Control control in c.Controls) { list.Add(control); if (control.GetType() == typeof(Panel)) GetAllControl(control , list); } } 

这就是我所做的,我编写了一个简单的函数,当我单击一个Button时,我只选择Panel Control并将其传递给一个函数,以进一步循环通过该面板上的控件。

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