如何动态制作按钮?
How Make a button dynamically?
我正在做一个 "list" 按钮,比如表单中的菜单,我正在尝试从数据库中的 table 中做这件事,我正在做这个像这样:
foreach (Catalogos catalogo in catalogos)
{
SimpleButton sb = new SimpleButton();
sb.Text = catalogo.Nombre;
sb.Click += catalogo.Evento;
LayoutControlItem item = new LayoutControlItem();
item.TextVisible = false;
item.Control = sb;
lcg.Add(item);
}
我的问题在 sb.Click += catalogo.Evento
行,我该如何动态地处理事件
使用 lambda / 匿名方法
SimpleButton sb = new SimpleButton();
sb.Text = catalogo.Nombre;
sb.Click += (sender, evntArgs) => {
//some dynamic mouse click handler here.
};
选项 1
在您的表单中创建一个 SimpleButton_Click
方法
private void SimpleButton_Click(object sender, EventArgs e)
{
//using (SimpleButton)sender you can find which botton is clicked
}
然后在你的循环中,将该方法分配给 Click
事件:
sb.Click += new System.EventHandler(this.SimpleButton_Click);
选项 2
以这种方式将 delegate/lambda 表达式分配给事件:
//instead of sender and e, usually you should use different names
//because usually you are running this code in an event handler
//that has sender and e parameters itself
sb.Click += (object senderObject, EventArgs eventArgs) =>
{
//using (SimpleButton)sender you can find which botton is clicked
};
我正在做一个 "list" 按钮,比如表单中的菜单,我正在尝试从数据库中的 table 中做这件事,我正在做这个像这样:
foreach (Catalogos catalogo in catalogos)
{
SimpleButton sb = new SimpleButton();
sb.Text = catalogo.Nombre;
sb.Click += catalogo.Evento;
LayoutControlItem item = new LayoutControlItem();
item.TextVisible = false;
item.Control = sb;
lcg.Add(item);
}
我的问题在 sb.Click += catalogo.Evento
行,我该如何动态地处理事件
使用 lambda / 匿名方法
SimpleButton sb = new SimpleButton();
sb.Text = catalogo.Nombre;
sb.Click += (sender, evntArgs) => {
//some dynamic mouse click handler here.
};
选项 1
在您的表单中创建一个 SimpleButton_Click
方法
private void SimpleButton_Click(object sender, EventArgs e)
{
//using (SimpleButton)sender you can find which botton is clicked
}
然后在你的循环中,将该方法分配给 Click
事件:
sb.Click += new System.EventHandler(this.SimpleButton_Click);
选项 2
以这种方式将 delegate/lambda 表达式分配给事件:
//instead of sender and e, usually you should use different names
//because usually you are running this code in an event handler
//that has sender and e parameters itself
sb.Click += (object senderObject, EventArgs eventArgs) =>
{
//using (SimpleButton)sender you can find which botton is clicked
};