views:

351

answers:

2

Hello,

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!

+6  A: 

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 Özgel
awesome! this totally helped. Thanks a bunch!
Jason Heine
A: 
    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