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#MongoDB使用Builders查找派生对象 2022-09-04
- C# 中多线程网络服务器的模式 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01