如何从不使用 TableLayoutPanel 的 Form 中获取控件?
How to get controls from Form that does not use TableLayoutPanel?
在使用 TableLayoutPanel 的 windows 表单应用程序中,我们通过函数
获得了所有控制权
Control control in tableLayoutPanel1.Controls
如果我不在我的表单中使用 TableLayoutPanel,有没有办法获取控件?
您可以创建如下扩展方法:
public static class ControlExtensions
{
public static IEnumerable<Control> GetAllControls(this Control containerControl)
{
var controls = Enumerable.Empty<Control>();
controls = controls.Concat(containerControl.Controls.Cast<Control>());
foreach (Control control in containerControl.Controls)
{
controls = controls.Concat(control.GetAllControls());
}
return controls;
}
}
并像这样使用它:
foreach (Control c in theForm.GetAllControls())
{
Debug.WriteLine(c.Name);
}
请注意,GetAllControls 方法可用于任何 Control
,而不仅仅是 Form
如果控件没有放在 TableLayoutPanel
中,那么它们很可能位于主窗体本身中。所以 ypu 可以像这样遍历它们:
foreach(Control control in this.Controls)
{
//do somthing with the controls
}
在使用 TableLayoutPanel 的 windows 表单应用程序中,我们通过函数
获得了所有控制权Control control in tableLayoutPanel1.Controls
如果我不在我的表单中使用 TableLayoutPanel,有没有办法获取控件?
您可以创建如下扩展方法:
public static class ControlExtensions
{
public static IEnumerable<Control> GetAllControls(this Control containerControl)
{
var controls = Enumerable.Empty<Control>();
controls = controls.Concat(containerControl.Controls.Cast<Control>());
foreach (Control control in containerControl.Controls)
{
controls = controls.Concat(control.GetAllControls());
}
return controls;
}
}
并像这样使用它:
foreach (Control c in theForm.GetAllControls())
{
Debug.WriteLine(c.Name);
}
请注意,GetAllControls 方法可用于任何 Control
,而不仅仅是 Form
如果控件没有放在 TableLayoutPanel
中,那么它们很可能位于主窗体本身中。所以 ypu 可以像这样遍历它们:
foreach(Control control in this.Controls)
{
//do somthing with the controls
}