Question

I have a custom control that can be added multiple times to a form. There can be multiples occurrences of this custom control on the same form. These controls are added and removed by the user. The user can right click on some control inside the custom control to reveal a menu.

When selecting an item from this menu, an event should be raised on the form. I made a custom event and realized that it could't be usable if the control was added dynamically, because the form doesn't know it. I can't add an event handler referring to a control that doesn't exist. Is there some other way to raise an event on the form from custom control that doesn't require the form to know it? By the way, my custom controls are added to a FlowLayoutPanel. Thanks for the help!

Was it helpful?

Solution

You just wire up the event handler in the code when you add the control e.g.

MyButton.Click += ButonClickEventHandler;
Page.Controls.Add(MyButton)

OTHER TIPS

Agree with Ben - otherwise, there are messy ways of doing it (depending on how your control is set up). For example INotifyPropertChanged Inerface or through Windows API messaging (and listener) - but unless you have a very strange set up, then as Ben said, simply add a handler when you add the control. You can always use a generic callback method and use custom event args to identify which has triggered it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top