Board index » delphi » How to create Events for Created controls

How to create Events for Created controls

I have an array of dynamically created objects is of type TButton, Can
anyone tell me how to create the required dynamic events (such as to
onclick event) associate with the dynamic button.

  for i := 1 to n do begin
    MyButton[i] := TButton.Create(Application);
    MyButton[i].Parent := form1;
    MyButton[i].Caption := Button+inttostr(i);
    etc...
end;

Thank you
James Tallent

 

Re:How to create Events for Created controls


[posted and mailed]

Quote
On Sat, 30 May 1998, James Tallent <soft...@flash.net> wrote:
>I have an array of dynamically created objects is of type TButton, Can
>anyone tell me how to create the required dynamic events (such as to
>onclick event) associate with the dynamic button.

>  for i := 1 to n do begin
>    MyButton[i] := TButton.Create(Application);
>    MyButton[i].Parent := form1;
>    MyButton[i].Caption := Button+inttostr(i);
>    etc...
>end;

>Thank you
>James Tallent

Assign the event handler as you do any property, e.g.,

MyButton[i].OnClick:=MyButtonClick;

Of course you need to define MyButtonClick.  Add it to your form
declaration:

TMyForm = class(TForm)
 ...
  procedure MyButtonClick( Sender:TObject);
 ...
end;

then define it in the implementation section:

procedure TMyForm.MyButtonClick( Sender:TObject);
begin
 ...
end;

-- luu

Please remove the underscore _ in my address when replying by email

Re:How to create Events for Created controls


In article <35707069.B5AF0...@flash.net>, James Tallent <soft...@flash.net>
writes:

Quote
>I have an array of dynamically created objects is of type TButton, Can
>anyone tell me how to create the required dynamic events (such as to
>onclick event) associate with the dynamic button.

You write your own event handler procedure which must be a method (ie defined
with a class prefix as in procedure TForm1.MyProc ).

Call it what you like but the parameters MUST be the same as the event
requires. Find this by looking at the type defined for that event in the help
file. For example OnClick has a procedure of type TNotifyEvent.  This is a
procedure which has one parameter called Sender of type TObject.

Then allocate it to the event handler's property.

So :-

procedure TForm1.MyOwnOnClick(Sender : TObject);
begin
 . . . etc etc . . .
Coding here has to identify which button is the sender if you're doing
different things or use different event handlers in your button create code
end;

In the "type TForm1 = class(TForm) . . . " declaration put :-

procedure MyOwnOnClick(Sender : TObject); {note NO TForm1 here}

then in your button creation loop :-

MyButton[i].OnClick := MyOwnOnClick;

or

Case i of
  0 : MyButton[i].OnClick := MyOwnButton0OnClick;
  4 : MyButton[i].OnClick := MyOwnButton4OnClick;
  else MyButton[i].OnClick := MyOwnOnClick;
end;

That's it.

Alan Lloyd
alangll...@ol.com

Other Threads