Yes. It should be something like:
foreach(Button button in allButtons) {
button.Click += (sender, eventArgs) {
ButtonClickHandler((Button)sender);
};
}
void ButtonClickHandler(Button button) {
}
But now, the problem is: OK, you use one handler for several buttons in this or some other ways. But do you really need to do exactly the same thing in response to a click of any of those buttons? Hardly. I would rather assume you want to do something different.
Here is what you would be tempted to do,
but should not:
void ButtonClickHandler(Button button) {
if (button == myFirstButton)
DoOneThing();
else if (button == mySeconfButton)
DoSomethineElse();
}
Can you see that it would completely defeat the purpose of one unified handler method? It could be much worse than adding its individual handler to each button. One common handler can only be useful when the handling it totally identical for all button, only
data
is different. But how to pass this data? In most cases, it would be enough to pass just the index of the button in the array, or something like that. It depends on the purpose of the buttons.
Something like this:
for(int index = 0; index < allButtons.Length; ++index) {
allButtons[index].Click += (sender, eventArgs) {
ButtonClickHandler(index);
};
}
void ButtonClickHandler(int index) {
}
Are you getting the idea?
To finish with the critical review of the idea of using the common handler, I need to note: the whole idea of using 20 buttons is questionable, and this is a root of the problem. Why? You could think about a list box and one button; the effect of button click would depends on the selection in the list box. The benefit of this would be this: in a list box, you can store any data, not just the string; the list box will display whatever is returned by
GetString
of the element type.
I mentioned the
closure in the code sample. It's very important to understand:
http://en.wikipedia.org/wiki/Closure_%28computer_science%29[
^].
—SA