How to add event handler for dynamically created controls at runtime?

前端 未结 3 554
独厮守ぢ
独厮守ぢ 2020-11-28 15:34

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 dyn

相关标签:
3条回答
  • 2020-11-28 15:57
    var t = new TextBox();
    t.MouseDoubleClick+=new System.Windows.Input.MouseButtonEventHandler(t_MouseDoubleClick);
    
    private void t_MouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
         throw new NotImplementedException();
    }
    

    It's adding double click eventhandler to new TextBox

    0 讨论(0)
  • 2020-11-28 16:05

    With anonymous method:

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

    With lambda syntax for an anonymous method:

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

    With method:

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

    Further information you can find in the MSDN Documentation.

    0 讨论(0)
  • 2020-11-28 16:07

    I believe you could do something like this:

    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.
    
    0 讨论(0)
提交回复
热议问题