Write code like this:
class ButtonHelper { }
void SetupButtonsVertically() {
Button button = new Button();
button.Click = delegate(object sender, EventArgs eventArgs) {
ButtonHelper buttonHelper = (ButtonHelper)((sender as Button).Tag);
};
button.Tag = new ButtonHelper(
button.Left = buttonLeft;
button.Top = currentY;
currectY += button.Height + yGap;
button.Text =
this.PanelSomewhereOnMyForm.Control.Add(button);
}
Call
SetupButtonsVertically
right after a call to
InitializeComponent
.
You can make more complex layout; this is just the idea.
Note the use of anonymous method: much more convenient way of programming events handlers. From the scope of
Button.Click
handler you can call any method, but unlike (morally obsolete) non-anonymous approach you're not bound to pass exact parameter list of
sender
and
eventArgs
.
Another useful trick is using
button.Tag
. You can put some useful information on the button function (of some helper class ButtonHelper) in its
Tag
(see
Control.Tag
). This
Tag
can be casted from
sender
in the handler to be used to implement click effect specific to a button instance.