如何动态制作按钮

本文关键字:按钮 动态 何动态 | 更新日期: 2023-09-27 18:12:09

我正在做一个按钮的"列表",就像一个表单中的菜单,我试图在数据库中的表中做到这一点,我这样做:

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.
};

option 1

在表单中创建一个SimpleButton_Click方法

private void SimpleButton_Click(object sender, EventArgs e)
{
    //using (SimpleButton)sender you can find which botton is clicked
}

然后在循环中,将该方法赋值给Click event:

sb.Click += new System.EventHandler(this.SimpleButton_Click);

选项2

为事件分配委托/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
};