tags:

views:

41

answers:

2

I created a custom control which is actually just two labels inside a panel. I want to add an event so that when my custom control is clicked (which would really be clicking either one of the labels) it would return the properties of the whole control, I think that would mean that 'sender' in the event handler would be my custom control and not one of the lables. I don't know if I made myself clear but what I mean is to treat the control as a 'whole' when it is clicked mmm anyway hope you get my point.

How can I do this? Thanks in advance

+1  A: 

What you can do is let the custom control consume the event of the label, and in the custom control implement a new event. Then, when the label event fires, you can fire your own event from the custom control.

For example:

public partial class UserControl1 : UserControl
{
    public UserControl1()
    {
        InitializeComponent();
    }

    public event EventHandler MyCustomClickEvent;

    protected virtual void OnMyCustomClickEvent(EventArgs e)
    {
        // Here, you use the "this" so it's your own control. You can also
        // customize the EventArgs to pass something you'd like.

        if (MyCustomClickEvent != null)
            MyCustomClickEvent(this, e);
    }

    private void label1_Click(object sender, EventArgs e)
    {
        OnMyCustomClickEvent(EventArgs.Empty);
    }
}
Pieter
Can you give me or point me to a code example? Thanks
VerizonW
Expanded the answer with an example.
Pieter
Thank you! it works, but I don't understand the code very well, what is the difference with using add/remove?
VerizonW
The difference is that with add/remove, you're faking your own event handler to that of the label. This is a more clean approach. Also, here you have the advantage that you can change the EventArgs you're sending to MyCustomClickEvent. You can create your own EventArgs class with your own parameters. This approach is advised over the add/remove approach because you keep more control over the events this way. Though about accepting the answer?
Pieter
Yes I will accept it thank you very much! just one more thing, if I have the two labels which cover all the visible area of the control then I assign label1_Click to both of them right?
VerizonW
Sure, why not. You can of course create a second and paste the OnMyCustomClickEvent line there too, but you can re-use the event.
Pieter
A: 

You can get the container object of your label and cast it to your custom control

private void Label1_Click(object sender, System.EventArgs e)
{
     Box box = (object as Label).Parent as Box;
     if(box != null)
     {
         //Do what you need here.
     }
}
Matt Ellen