I am looking for a way to use one procedure for multiple buttons. It's for a quiz like you have to press Button 1 for question 1, but copy and pasting the whole code for 36 buttons and changing the variables for 36 buttons isn't really fun for anybody.
So I thought something like this would be possible:
procedure TForm1.Button[x]Click(Sender: TObject);
begin
DoTask[x];
end;
X being the variable.
Is something like that possible or are there other ways to acquire the same result?
The easiest way to do this is:
Number the buttons using the Tag
property in the Object Inspector (or in code when they're created) in order to easily tell them apart. (Or assign the value you want to be passed to your procedure/function when that button is clicked.)
Create one event handler, and assign it to all of the buttons you want to be handled by the same code.
The Sender
parameter the event receives will be the button that was clicked, which you can then cast as a TButton
.
procedure TForm1.ButtonsClick(Sender: TObject);
var
TheButton: TButton;
begin
TheButton := Sender as TButton;
DoTask(TheButton.Tag);
end;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With