Question:
How can I create a function that attaches multiple event handlers to multiple controls?
Intent:
I am using C# to develop a windows forms application. I want to create a function that takes a collection of controls and a collection of event handlers. This function will attach the event handlers to the controls. What would be the most elegant, and reusable way to do this. I have a pretty ugly way to do this with delegates, but it is a but it is less work for me to just throw this into a loop, and abandoning the function.
Behavior I basically want:
foreach(Control control in controlCollection)
foreach(EventHandler handler in eventHandlerCollection)
control.Event += handler;
Function:
attachHandlers(? controlCollection, ? eventHandlers)
Edit:
I am just going to subscribe all the handlers to the same event on all the controls. I didn’t explicitly say that in my description, so I believe that is the reason for all of confusion.
If the controls in question inherit from the same base class or interface (or they are the same class), you can do something like:
This assumes an interface like: