Reputation: 2020
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.
Upvotes: 1
Views: 282
Reputation: 39085
If the controls in question inherit from the same base class or interface (or they are the same class), you can do something like:
void AttachClickEventHandlers(List<IClickableControl> controls, List<MyClickHandler> eventHandlers)
{
foreach (var control in controls)
foreach (MyClickHandler handler in eventHandlers)
control.Click += handler;
}
This assumes an interface like:
public interface IClickableControl
{
event MyClickHandler Click;
}
Upvotes: 2