获取表格中的所有按钮,包括 相同形式的面板中的按钮..
答案 0 :(得分:10)
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);
}
}
答案 1 :(得分:5)
这是我所做的, 我写了一个简单的函数,当我单击一个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);
}
}
答案 2 :(得分:1)
试试这个
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
}
}
}
}