code OnClick event handlers for array of buttons delphi

3.1k Views Asked by At

Basically what I'm trying to do is create an array of Tbutton at runtime and have OnClick event handlers for each button created. the creation of the buttons works fine and please excuse the feeble attempt at trying to get the OnClick part of things right. Have googled extensively but to no avail. i tried to follow the code at http://docwiki.embarcadero.com/RADStudio/XE5/en/Events but struggled to follow. Not sure if it is what i was looking for anyway.

  procedure this(sender:TObject);
  end;

var
  Form1: TForm1;
  x: Integer;
  y: Integer;
  p:array [1..3,1..3] of Tbutton;


implementation

{$R *.dfm}

procedure TForm1.t(Sender: TObject);

begin
for x := 1 to 3 do
  for y := 1 to 3 do
      begin
         p[x,y]:=tbutton.Create(nil);
         p[x,y].Parent:=form1;
         p[x,y].height:=Round(Height/3);
         p[x,y].Width:=Round(width/3);
         p[x,y].Left:=(x-1)*(p[x,y].Width);
         p[x,y].Top:=(y-1)*(p[x,y].height);
         p[x,y].OnClick:=this;
      end;
end;

procedure TForm1.this(sender: TObject);
begin
p[x,y].Caption:='avasfd';
end;

end.  

Thanks. -Benjamin.

2

There are 2 best solutions below

0
On

You need to cast Sender as TButton. i.e.

TButton(Sender).Caption := 'avasfd';
2
On

You'll need to typecast the Sender in the event handler (it will be the button clicked):

procedure TForm1.this(sender: TObject);
begin
    (Sender as TButton).Caption := 'avasfd';
end;

BTW, this is a terrible name for an event handler. It would be much better to use something descriptive, so that later when you (or someone else) reads the code it's clear what it's for. Something like this, for instance:

procedure TForm1.ButtonFromArrayClick(Sender: TObject);