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

1

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?

Coremaker answered 5/1, 2015 at 18:49 Comment(1)
Retrieve "x" from tbutton(sender).name instead ? Just scan backwards for numeric digits.Larisa
K
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;
    
Knossos answered 5/1, 2015 at 18:54 Comment(4)
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.Coremaker
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.)Knossos
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 reasonCoremaker
QuestionNumber := (Sender as TButton).Tag works, as does TButton(Sender).Tag (as long as you're sure Sender is a TButton).Knossos

© 2022 - 2024 — McMap. All rights reserved.