【问题标题】:How to add event handler for dynamically created controls at runtime?如何在运行时为动态创建的控件添加事件处理程序?
【发布时间】:2013-07-25 10:27:00
【问题描述】:

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

例如:

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

【问题讨论】:

    标签: c# winforms


    【解决方案1】:

    使用匿名方法:

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

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

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

    使用匿名方法的 lambda 语法:

    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 Documentation 中找到更多信息。

    【讨论】:

      【解决方案2】:
      var t = new TextBox();
      t.MouseDoubleClick+=new System.Windows.Input.MouseButtonEventHandler(t_MouseDoubleClick);
      
      private void t_MouseDoubleClick(object sender, MouseButtonEventArgs e)
      {
           throw new NotImplementedException();
      }
      

      它将双击事件处理程序添加到新的文本框

      【讨论】:

        【解决方案3】:

        我相信你可以这样做:

        if (userCanAdd)
            container.Controls.Add(GetAddButton());
        if (userCanUpdate)
            container.Controls.Add(GetUpdateButton());
        if (userCanDelete)
            container.Controls.Add(GetDeleteButton());
        
        private Button GetAddButton() {
            var addButton = new Button();
            // init properties here
        
            addButton.Click += (s,e) => { /* add logic here */ };
            // addButton.Click += (s,e) => Add();
            // addButton.Click += OnAddButtonClick;
        
            return addButton;
        }
        
        private void OnAddButtonClick (object sender, EventArgs e) { 
            // add logic here
        }
        
        // The other methods are similar to the GetAddButton method.
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-12-24
          相关资源
          最近更新 更多