There is nothing weird in this situation. To tell you more, there are many very similar questions here at CodeProject; this topic is actually one of the popular ones. No wonder, this situation is very natural.
Now, there can be different solutions, but there is nothing tricky at all.
Here is one of the ways which I think is robust enough. Another good thing: it can be used with
both WPF and
System.Windows.Forms
.
(You need to uniquely identify the button. Many advise to use the name or even button text. Please, never do that! It is not a supportable way.)
Instead of attempting to identify a button, put some information in its tag. It should be some information we use at the moment of click, and can be anything: enumeration (what kind of action to take), a structure or a class (data used at the moment of click, such as database key or what ever):
internal class ButtonClickInfo {
internal ButtonClickInfo() { }
}
Now, for every button, add an appropriate instance of this type and appropriate handler:
Button btn;
btn.Tag = new ButtonClickInfo(
btn.Click += (sender, eventArgs) => {
Button thisButton = (Button)sender;
ButtonClickInfo info = (ButtonClickInfo)(thisButton.Tag);
PerformButtonClickActionDependingOnButtonClickInfo(info);
};
You can automate this procedure of setting Tags and Click event handlers: parametrize the data passed to tag (this should be the only difference between buttons) and run it in some loop, depending on item data, etc.
Now, pay attention: thanks to the anonymous delegate, you do not have to pass any of the unused parameters like
sender
and
eventArgs
to the handler method; you already extracted
ButtonClickInfo
instance from the
Button
instance, and this is all what matters. You pass only essential data to
PerformButtonClickActionDependingOnButtonClickInfo
. Therefore, I don't recomment using any event handlers auto-generated by the Designed: it will generate obsolete-style code which is hard to support. Doing it by coding the way I illustrated above is much faster and better for supportability.
—SA