C# create an array of controls(C# 创建控件数组)
问题描述
是否可以创建控件数组?如果数组中的多个控件共享同一个事件处理程序,有没有办法获取控件的索引?
Is it possible to create an array of controls? Is there a way to get the index of a control if more than one of the controls in the array share the same event handler?
推荐答案
这当然是可以做到的.在这种情况下,共享事件处理程序相当容易,因为引发事件的 Button
是作为事件参数的一部分发送的.它将是 sender
值,并且可以转换回 Button
This is certainly possible to do. Sharing the event handler is fairly easy to do in this case because the Button
which raised the event is sent as part of the event args. It will be the sender
value and can be cast back to a Button
这里是一些示例代码
class Form1 : Form {
private Button[] _buttons;
public Form1(int count) {
_buttons = new Button[count];
for ( int i = 0; i < count; i++ ) {
var b = new Button();
b.Text = "Button" + i.ToString()
b.Click += new EventHandler(OnButtonClick);
_buttons[i] = b;
}
}
private void OnButtonClick(object sender, EventArgs e) {
var whichButton = (Button)sender;
...
}
}
这篇关于C# 创建控件数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C# 创建控件数组


基础教程推荐
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01