0

我正在做一个按钮的“列表”,比如表单中的菜单,我正在尝试从数据库中的表中完成它,我这样做是这样的:

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在线,我怎样才能动态地做事件

4

2 回答 2

3

使用 lambda / 匿名方法

SimpleButton sb = new SimpleButton();
sb.Text = catalogo.Nombre;
sb.Click += (sender, evntArgs) => {
    //some dynamic mouse click handler here.
};
于 2015-09-11T01:12:29.470 回答
1

选项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

以这种方式将委托/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
};
于 2015-09-11T01:26:20.317 回答