Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Click event is not firing when I click a control in dynamic usercontrol

I have different controls in my usercontrols. And load usercontrols dynamically in my form

UserControl2 usercontrol = new UserControl2();
usercontrol.Tag = i;
usercontrol.Click += usercontrol_Click;
flowLayoutPanel1.Controls.Add(usercontrol);

private void usercontrol_Click(object sender, EventArgs e)
{
   // handle event
}

The click event is not firing when I click a control in usercontrol. It only fires when I click on empty area of usercontrol.

like image 257
Karlx Swanovski Avatar asked Jun 05 '13 12:06

Karlx Swanovski


2 Answers

Recurse through all the controls and wire up the Click() event of each to the same handler. From there call InvokeOnClick(). Now clicking on anything will fire the Click() event of the main UserControl:

public partial class UserControl2 : UserControl
{

    public UserControl2()
    {
        InitializeComponent();
        WireAllControls(this);
    }

    private void WireAllControls(Control cont)
    {
        foreach (Control ctl in cont.Controls)
        {
            ctl.Click += ctl_Click;
            if (ctl.HasChildren)
            {
                WireAllControls(ctl);
            }
        }
    }

    private void ctl_Click(object sender, EventArgs e)
    {
        this.InvokeOnClick(this, EventArgs.Empty); 
    }

}
like image 68
Idle_Mind Avatar answered Nov 09 '22 23:11

Idle_Mind


This should solve your problem.

//Event Handler for dynamic controls
usercontrol.Click += new EventHandler(usercontrol_Click); 
like image 39
Apollo Avatar answered Nov 09 '22 23:11

Apollo