We help IT Professionals succeed at work.

Buttons created at runtime in Delphi 4

RalphPorter
RalphPorter asked
on
Hi folks,

I have a set of buttons created dynamically at runtime from database records, these combine to make a switchboard type selection. Each button has a unique caption which is in fact a speaking key to the user amd the data base. I have assigned the same onclick procedure to every button. My question is how do I retrieve the button caption from within the onclick event? I thought I would get it from the sender object but this appears to be empty. Also how do I ensure that all the buttons are destroyed when the user changes switchboards. Thanks.
Comment
Watch Question

You could do it llike this:

procedure TForm1.Button1Click(Sender: TObject);
begin
  if TButton(Sender).Caption = 'Test Button 1' then
    ShowMessage('Test Button 1');
end;

Cheers,

Alan
Commented:
For captions do this:
procedure TForm1.CommonButtonClick(Sender: TObject);
begin
  (Sender as TButton).Caption := 'some_caption';
end;

For total destruction, use a TList object.
when the field data is retrieved from the database, create the btn and add it to you list
On_Field_Data_Come_in_Event:
  btn := TButton.Create(self);
  with btn do
  begin
    Parent := self;
    Onclick := CommmonButtonClick;
    ...
    Caption := '...';
    ... //set other properties
  end;
  buttonList.Add(btn);

On_switchbrd_change_event:
  for i := 0 to buttonList.count-1 do
  begin
    btn := TButton(buttonList[i]);
    btn.Free;
  end;
  buttonList.Clear;

Author

Commented:
Rondi - Thanks that little piece of syntax (Sender as TButton).Caption was what I needed and thank you for the destruction routine as well.

What I had was (don't laugh):

With sender as tbutton do
Key := sender.caption;

Couldn't understand why it complaining about caption being undeclared

Of course I realise now I look at it again why it doesn't work DUH :)

Alanwhincup Thanks as well that also works for me.

Commented:
*giggling* Glad to help, Ralph ;)

Explore More ContentExplore courses, solutions, and other research materials related to this topic.