Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

event handling for dynamically generated components

Status
Not open for further replies.

ladoota

Technical User
Jun 14, 2002
2
0
0
SI
In my application I need to generate a number of components (of the same kind) on the fly. I ran into difficulties how to handle the events, triggered by them as I have to know where it comes from. Browsing the docs, faq's and forums did not give me an idea, how can I detect which of the components triggered the event?

So for example: I create 2 TButton components on-the-fly (Btn1, Btn2). In both I declare OnClick:=HandleTheclicks;
Now procedure HandleTheClicks(Sender:TObject) works OK, except that I need to find out which button fired the event.

An example or a pointer to an explanation is welcome.

Regards, Vladimir
 
TButton(Sender) gives you the button that called the event.
For example;
Code:
if TButton(Sender) = Btn1 then //btn1 was pressed
etc
 
And then there is also the ever usefull Tag property that can bet set to some integer value during creation of the TButtons() and to be checked later... like in:

case TButton(sender).tag of
1 : Close; // Kill app
2 : ProcessSecondButton; // Do something else
...
end;

HTH,
TonHu
 
I would like to say I prefer MikeEd's method, but I don't. This code won't compile since btn1 isn't created at designtime yet.

You also don't have to typecast the component unless you need some specific properties of the component:

procedure HandleMyEvents(Sender: TObject);
begin
if not (Sender is TWinControl) then
Exit;
if TWinControl(Sender).Tag = 1 then
Close; // Tag 1 components kill the app in this exmpl.

if (Sender is TCombobox) then
with TComboBox(Sender) do
if ItemIndex > -1 then // Yay! I selected something.
ShowMessage( 'You selected ' + Items[ItemIndex] + ' from the list.' );
end;
 
GolezTrol, that code will compile as long as the variable Btn1 is visible to the HandleTheClicks procedure.
 
If you name the component on creation, then you can address the button this way:

If (Sender as TWinControl).Name = 'Button1' then
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top