9

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!

CodeLikeBeaker
  • 20,682
  • 14
  • 79
  • 108

2 Answers2

12

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.

Serhat Ozgel
  • 23,496
  • 29
  • 102
  • 138
  • awesome! this totally helped. Thanks a bunch! – CodeLikeBeaker Jul 02 '09 at 00:18
  • 1
    Thank you!!! Please note that you should include a recursive add/remove for Controls that are inside Controls (For example Controls inside a Panel) – Gerhard Powell May 01 '12 at 14:49
  • Also you shouldn't forget to check the object types in your event-method: `public void MyUserControl_Click(Object sender, EventArgs e) { if(sender.GetType() is Label) {...} } `. Otherwise you could easily run into problems. – libjup Aug 04 '12 at 22:02
0
    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.

Phoexo
  • 2,485
  • 4
  • 25
  • 33