如何在运行时为动态创建的控件添加事件处理程序? [英] How to add event handler for dynamically created controls at runtime?

查看:71
本文介绍了如何在运行时为动态创建的控件添加事件处理程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用C#Windows应用程序。我的应用程序从自定义控件库中获取控件(按钮,文本框,富文本框和组合框等),并在运行时动态地将其放入表单中。如何使用委托为该控件创建事件处理程序?以及如何在特定的自定义控件点击事件中添加业务逻辑?

I am working on C# windows application. my application get controls(button,text box,rich text box and combo box etc)from custom control library and placed them into form dynamically at run time. how i create event handler for that controls using delegate? and how to add business logic in particular custom control click event?

例如:

我有user1, user2,user3,当user1登录时,我只想显示保存按钮。当user2然后仅显示添加和删除按钮,而用户3仅显示添加和更新按钮时。根据用户创建的文本框和按钮登录从DB表中获取的信息。在这种情况下,我如何处理不同的事件(添加,保存,更新,删除),用于在动态创建表单控件时保存,添加,删除和更新按钮(保存,添加,删除和更新按钮对象来自同一按钮类)

i have user1, user2, user3, when user1 log in i want to show only "save" button. when user2 then only show "add and delete" buttons and user 3 only show "add and update" buttons.text boxes and button created as per user log in information taken from DB tables.in this scenario how i handle different event(adding,saving,updating,deleting) for button save,add,delete and update for different users when form is dynamically created controls(save,add,delete and update button object is from same button class)

推荐答案

使用匿名方法:

Button button1 = new Button();
button1.Click += delegate
                    {
                        // Do something 
                    };

使用带有显式参数的匿名方法:

With an anonymous method with explicit parameters:

Button button1 = new Button();
button1.Click += delegate (object sender, EventArgs e)
                    {
                        // Do something 
                    };

使用lambda语法表示匿名方法:

With lambda syntax for an anonymous method:

Button button1 = new Button();
button1.Click += (object sender, EventArgs e) =>
                    {
                        // Do something 
                    };

使用方法:

Button button1 = new Button();
button1.Click += button1_Click;

private void button1_Click(object sender, EventArgs e)
{
    // Do something
}

您可以在 MSDN文档

这篇关于如何在运行时为动态创建的控件添加事件处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆