7

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?

Kromster
  • 7,181
  • 7
  • 63
  • 111

1 Answers1

7

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;
    
Ken White
  • 123,280
  • 14
  • 225
  • 444
  • Well, thank you kindly sir for the help. However I am fairly if not really inexperienced with Pascal so...Could elaborate on step 2 if you would be so kind? Like I don't really know how to use Event Handler let alone create one from scratch even if it's a basic one. – Pascalerino Jan 06 '15 at 20:12
  • Double-click on any one of the buttons in the IDE, which will create the shell of the routine (for instance, `Button1Click`). Use the Events tab for that button in the Object Inspector to rename it to something more generic (such as `ButtonsClick`). Ctrl-click all of the buttons on the form that you want to share the same event, switch to the Object Inspector Events tab, and select that generic `ButtonsClick` event as the OnClick handler for all the buttons. (Or simply assign it to each of them separately using the Object Inspector.) – Ken White Jan 06 '15 at 20:18
  • Well thanks that makes it much clearer! But one more quick question is how can I assign the Tbutton.tag to a variable? QuestionNumber:= TButton.Tag; won't work for obvious reason – Pascalerino Jan 06 '15 at 20:41
  • `QuestionNumber := (Sender as TButton).Tag` works, as does `TButton(Sender).Tag` (as long as you're sure `Sender` is a `TButton`). – Ken White Jan 06 '15 at 20:56