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

自闭症网瘾萝莉.ら 提交于 2019-11-30 05:05:56

问题


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.


回答1:


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

}



回答2:


This should solve your problem.

//Event Handler for dynamic controls
usercontrol.Click += new EventHandler(usercontrol_Click); 



回答3:


Take this:

this.btnApply.Click += new System.EventHandler(this.btnApply_Click);




回答4:


Because events from ChildControls are not propagated to parents. So you have to handle Click event on every child control added to UserControl.




回答5:


1-define a delegate at nameapace

public delegate void NavigationClick(int Code, string Title);

2-define a event from your delegate in UserControl class:

        public  event NavigationClick navigationClick;

3-write this code for your control event in UserControl:

private void btn_first_Click(object sender, EventArgs e)
    {
        navigationClick(101, "First");
    }

4-in your Windows Form than use from your UserControl at Event add:

private void dataBaseNavigation1_navigationClick(int Code, string Title)
    {
        MessageBox.Show(Code + " " + Title);
    }


来源:https://stackoverflow.com/questions/16940270/click-event-is-not-firing-when-i-click-a-control-in-dynamic-usercontrol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!