Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OnClick event for dynamic button?

Tags:

events

delphi

Before I start I must state that no other stack overflow post on this topic had helped me yet

I have a dynamic button called by btnApply

It is created dynamically on a dynamic form frmSort by a on click event of static button btnSort on static form frmTable

Under the global scope var of frmTable is declared

btnApply: TButton;
Procedure btnApplyClick(Sender:TObject);
//other vars

Under the btnSort on click

//other code
btnApply:= TButton.create(frmSort);
//all its properties
BtnApply.onclick:= btnApplyClick;
//other code

Then later

Procedure btnApplyClick(Sender:TObject);
Begin
  //it's code it has to execute
End;

I get an error message at the "BtnApply.onclick:= btnApplyClick;" Line of incompatible types between method pointer and regular procedure

How do I make this work?

Thanks in advance

like image 210
RaymondSWalters Avatar asked Oct 20 '15 17:10

RaymondSWalters


People also ask

How to call onclick function on dynamically created button in JavaScript?

onclick = function () { alert("hi jaavscript"); };

How do you create a dynamic button?

Android App Development for Beginners This example demonstrates how do I add a button dynamically in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.


1 Answers

Your btnApplyClick needs to be a method of an object. Since the button has to be on a form to be useful anyway, make it a method of the form itself:

type
  TfrmSort = class(TForm)
    // UI controls listed here
  public
    procedure btnApplyClick(Sender: TObject);
  end;

implementation

procedure TfrmSort.btnApplyClick(Sender: TObject);
begin
  (Sender as TButton).Caption := 'You clicked me';
end;

procedure TfrmSort.FormCreate(Sender: TObject);
var
  Btn: TButton;
begin
  Btn := TButton.Create(Self);
  Btn.Parent := Self;
  Btn.Top := 100;
  Btn.Left := 100;
  Btn.OnClick := btnApplyClick;
end;

If for some reason you can't make it a form method (although I can't see how this would be the case for a visual control), you can make it a method of any object, like this:

implementation

// You must use StdCtrls in order to have the types available if
// it's not already in your uses clause
type
  TDummyButtonClickObj = class
    class procedure ButtonClickHandler(Sender: TObject);
  end;

{ TDummyButtonClickObj }

class procedure TDummyButtonClickObj.ButtonClickHandler(Sender: TObject);
begin
  (Sender as TButton).Caption := 'You clicked me.';
end;

procedure TForm2.FormCreate(Sender: TObject);
begin
  with TButton.Create(Self) do
  begin
    Parent := Self;
    Top := 100;
    Left := 100;
    Caption := 'Click here';
    OnClick := TDummyButtonClickObj.ButtonClickHandler;
  end;
end;
like image 93
Ken White Avatar answered Sep 28 '22 13:09

Ken White