Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to use ONE procedure for multiple buttons in Pascal?

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?

like image 697
Pascalerino Avatar asked Jan 05 '15 18:01

Pascalerino


1 Answers

The easiest way to do this is:

  1. 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.)

  2. Create one event handler, and assign it to all of the buttons you want to be handled by the same code.

  3. 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;
    
like image 154
Ken White Avatar answered Sep 22 '22 18:09

Ken White