[英]Collect controls in a form c#
I have a form in which there are some buttons. 我有一个表格,里面有一些按钮。 I'd like put their references in an array.Is it possible with a foreach ? 我想将它们的引用放在一个数组中。foreach是否可能?
I want to do this: 我想做这个:
public Form1()
{
InitializeComponent();
Button[] all = new Button[5];
all[0] = button1;
all[1] = button2;
all[3] = button3;
all[4] = button4;
}
I've already tried 我已经尝试过了
int i=0;
foreach (Button p in Form1)
{
all[i]= p;
i++;
}
But I can't use a foreach on a Form. 但是我不能在Form上使用foreach。 The same thing if the buttons are in a panel. 如果按钮在面板中,也是一样。
What can I do to collect all buttons quickly? 如何快速收集所有按钮? Thanks :) 谢谢 :)
You're looking for the Controls
collection of your form or container, which contains every control directly in it. 您正在寻找表单或容器的Controls
集合,其中直接包含每个控件。
Beware that this will also include non-Buttons; 注意,这还将包括非按钮; call .OfType<Button>()
to filter. 调用.OfType<Button>()
进行过滤。
So instead of the foreach you can initialize an array like this: 因此,您可以像这样初始化数组而不是foreach:
Button[] all = this.Controls.OfType<Button>().ToArray();
Every Control
has a Controls
property which is a ControlCollection
. 每个Control
都有一个Controls
属性,该属性是ControlCollection
。 You can get all Button
s on a Control
(as a Form
or a Panel
) like this: 您可以像这样在Control
(作为Form
或Panel
)上获取所有Button
:
foreach(var button in control.Controls.OfType<Button>())
{ ... }
But this will only give you the Button
s that are contained directly by this control
. 但这只会给您直接由此control
包含的Button
。 If you want to get all Button
s in your Form
on all Panel
s, GroupBox
s etc, you need to recurse through the Controls
like in this example: 如果要在所有 Panel
, GroupBox
等等上的Form
获取所有Button
,则需要像下面的示例一样通过Controls
进行递归:
public class Form1 : Form
{
// ...
private static IEnumerable<Button> GetAllButtons(Control control)
{
return control.Controls.OfType<Button>().Concat(control.Controls.OfType<Control>().SelectMany(GetAllButtons));
}
private void DoSomethingWithAllButtons()
{
foreach(var button in GetAllButtons(this))
{ // do something with button }
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.