获取一个表单中所有的按钮,包括同一表单面板中的按钮。
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
}
}
}
}