从现有按钮创建按钮数组(集合) [英] Create array (collection) of buttons from existing buttons
问题描述
是否有一种简单的方法可以从表单上的现有按钮创建按钮集合? (在C#中)。
is there a simple way of creating a button collection from the existing buttons on my form? (In c#).
我的表单上已经有一系列按钮,我想使用索引来访问它们……例如:
I have a series of buttons already on my form and I want to use an index to access them...e.g.:
myButtonArray[0].ForeColor ...// Do something with it
可以这样做吗?
编辑:我可以将数组设置为具有通用的OnClick事件吗?然后确定单击数组中的哪个按钮,然后更改其颜色?
Can I set the array to have a generic OnClick event? And then determine which button in the array was clicked and, say, change its color?
推荐答案
您可以用相同的方法和其他数组一样例如:
You can do it the same way as for any other array. For example:
Button[] array = { firstButton, secondButton };
或者如果您需要在一个地方声明并稍后分配:
or if you need to declare in one place and assign later:
Button[] array;
...
array = new Button[] { firstButton, secondButton };
在C#3+中,可以将隐式类型用于数组初始化程序:
In C# 3+ you can use implicit typing for array initializers:
Button[] array;
...
array = new[] { firstButton, secondButton };
您可能还想考虑使用 List< Button>
:
List<Button> buttons = new List<Button> { firstButton, secondButton };
这篇关于从现有按钮创建按钮数组(集合)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!