0

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
  • so what is the question? Commented Dec 5, 2013 at 16:54
  • use TButton(sender).Caption := 'avasf' Commented Dec 5, 2013 at 16:55

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Actually you usually want that runtime exception. So you would use (Sender as TButton).Caption := ... That way you get an error when you click on the button rather than a button that does nothing. That's generally preferable. Then you discover that your code is broken.
@David: Actually, I usually just write TButton(Sender) unless I'm intentionally using the handler for different types, in which case I use is to differentiate between types. I haven't shot myself in the foot more than once or twice, and they've been rare enough that the scars have all but disappeared. :-) When it happens now, it's usually when I'm figuring out a new component or class, and make a mistake about what is sending the event. You're right, though; better advice for a newer user. Updated.
1

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

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

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.