Search code examples
c#winformscustom-controlscustom-event

Raising event from custom control added dynamically to the form


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!


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)