从现有按钮创建按钮数组(集合)
有没有一种简单的方法可以从表单上的现有按钮创建按钮集合? (在 c# 中)。
我的表单上已经有一系列按钮,我想使用索引来访问它们...例如:
myButtonArray[0].ForeColor ...// Do something with it
可以这样做吗?
编辑:我可以将数组设置为具有通用 OnClick 事件吗?然后确定单击了数组中的哪个按钮,例如更改其颜色?
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
Can this be done?
Edit: 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
LINQ 来救援!
LINQ to the rescue!!
您可以按照与任何其他数组相同的方式进行操作。例如:
或者如果您需要在一处声明并稍后分配:
在 C# 3+ 中,您可以对数组初始值设定项使用隐式类型:
您可能还需要考虑使用
List
You can do it the same way as for any other array. For example:
or if you need to declare in one place and assign later:
In C# 3+ you can use implicit typing for array initializers:
You might also want to consider using a
List<Button>
instead:如果有很多按钮,要简化此过程,您可以在表单级别尝试此代码:
您可以使用 Controls 集合中具有非空 Controls 集合本身的任何 Control 来递归此代码。
To streamline this process if there are a lot of Buttons, you could try this code at the form level:
You could recurse this with any Control in the Controls collection that has a nonempty Controls collection itself.
像这样的东西:
something like:
所有控件都位于表单的 Controls 属性中,因此您必须迭代该集合并将其添加到数组中。
You have all your controls in the Controls property of your form, so you have to iterate that collection and add it to your array.
响应您的要求:
(
编辑:我可以将数组设置为具有通用 OnClick 事件吗?然后确定单击了数组中的哪个按钮,然后更改它的颜色?
)In response to your requirements:
(
Edit: 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?
)如果您使用的是 C# 7.0 或更高版本,则可以使用
is
关键字在循环访问每个控件时检查它们是否为按钮。对于旧版本的 C#,请参阅 @Edgar Hernandez 的 答案
If you are using C# 7.0 or higher you can use the
is
keyword to check if each control is a button as you loop through them.For older versions of C# please see @Edgar Hernandez's answer
假设有命名约定...
Assuming there is a naming convention...