简体   繁体   中英

User Control Click - Windows Forms

I have a custom user control on my windows forms. This control has a few labels on it.

I will be dynamically displaying an array of these controls on my form which will contain different bits of data.

What I am trying to do is know which user control was selected when I click on it.

This works when I click on an empty space on the user control, however, if I click on any label on the user control it will not recognize the user control click.

Any thoughts on how I can do a full user control click, even if a label on the control is being clicked?

If this question is not clear, or you need more info, please leave a comment.

I am doing this in c#.

Thanks!

User control's click event won't fire when another control is clicked on the user control. You need to manually bind each element's click event. You can do this with a simple loop on the user control's codebehind:

foreach (Control control in Controls)
{
    // I am assuming MyUserControl_Click handles the click event of the user control.
    control.Click += MyUserControl_Click;
}

After this piece of code workd, MyUserControl_Click will fire when any control on the user control is clicked.

    foreach (Control c in this.Controls)
    {
        c.Click += new EventHandler(SameAsForm_Click);
    }

Keep in mind that this won't add labels' clickevents in groupboxes, panels etc to the "SameAsForm_Click"-EventHandler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM