0

I need assistance for trying to get the name of a dynamically created button using and OnClick event in Delphi.

I am then want to use the name of that button and store it in a global variable.

This is where I am currently:

procedure TMap.FormShow(Sender: TObject);
var
btnCache : TButton;
begin
 btnCache := TButton.Create(imgAerial);
 with btnCache do
 begin
  onclick := ClickButton;
 end;

procedure TMap.ClickButton(Sender: TObject);
begin
//Code for getting the name of the button
end;   
2
  • 1
    Do you intend to reference the control by this name? Because that won't be possible. You should refer to it by its variable. The name only means anything if you drop it into the form through the IDE (auto-create). Not only don't you assign a name, but even if you do, that name is only a string. As David mentions in his answer, don't expect that name to mean much. If you want to access this button from elsewhere, declare your variable btnCache in the form, not in this private procedure. Commented Oct 16, 2014 at 18:06
  • 1
    Why would you need the name at all? You know that when ClickButton is called, Sender is the button that was clicked, so just use a local variable of type TButton, and assign it the value of Sender with a typecast like MyBtn := (Sender as TButton);. You can then use MyBtn in the code as usual. If your code depends on the string name of the button, you've designed your code wrong. Commented Oct 16, 2014 at 20:10

1 Answer 1

4

The button's name can be retrieved by casting Sender to the type that introduces Name. That is TComponent.

(Sender as TComponent).Name

Don't expect this name to be very informative since your code does not assign a name to the button. As the code is written in the question, the dynamically created button has no name.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.