我正在尝试使用Button
中使用的所有Form1
来填充数组。
Button[] ButtonArray = new Button[5];
ButtonArray[0] = button1;
ButtonArray[1] = button2;
ButtonArray[2] = button3;
ButtonArray[3] = button4;
ButtonArray[4] = button5;
此代码工作正常。 但是,如果我有 100 按钮,这是一个很长的过程。
答案 0 :(得分:16)
如果表单上有所有Button
,您可以尝试使用 Linq :
using System.Linq;
...
Button[] ButtonArray = Controls
.OfType<Button>()
.ToArray();
修改:如果 groupboxes 中有一些按钮,面板(即表单上没有直接) ,但在某种容器)上,你必须将代码详细说明为
private static IEnumerable<Button> GetAllButtons(Control control) {
IEnumerable<Control> controls = control.Controls.OfType<Control>();
return controls
.OfType<Button>()
.Concat<Button>(controls
.SelectMany(ctrl => GetAllButtons(ctrl)));
}
...
Button[] ButtonArray = GetAllButtons(this).ToArray();
有关详细信息,请参阅How to get ALL child controls of a Windows Forms form of a specific type (Button/Textbox)?
答案 1 :(得分:3)
你可以尝试这个:
ButtonArray[] buttonArray = new ButtonArray[this.Controls.OfType<Button>().Count()]
int i =0; //index for button array
foreach(var button in this.Controls.OfType<Button>()) //Iterate through each button control
{
buttonArray [i++] = button;
}
答案 2 :(得分:3)
Enumerable.OfType
不会在控件层次结构中搜索控件。因此,如果您想以递归方式查找控件,可以使用此扩展方法:
public static IEnumerable<T> RecursiveControlsOfType<T>(this Control rootControl) where T : Control
{
foreach (Control child in rootControl.Controls)
{
if (child is T targetControl)
yield return targetControl;
foreach (T targetControlChild in child.RecursiveControlsOfType<T>())
yield return targetControlChild;
}
}
用法:
Button[] nonRecursiveButtons = this.Controls.OfType<Button>().ToArray();
Button[] recursiveButtons = this.RecursiveControlsOfType<Button>().ToArray();
答案 3 :(得分:1)
List<Button> Buttons = new List<Button>();
foreach (var item in this.Controls) // Looping through all controls in the form
{
if (item is Button) // if the current is a button we add it
{
Buttons.Add(item as Button);
}
}