Link to home
Start Free TrialLog in
Avatar of red_2
red_2

asked on

Arrays of visual components

Is there an easy way to create an array of visual components? I'm going to use a lot of buttons, and I want to arrange them in an array so I don't need to write an eventhandler for each one of them. Is this possible?
Avatar of JimBob091197
JimBob091197

You can use a TList, which contains a list of pointers to objects.
E.g.
MyList := TList.Create;
MyList.Add(Button1);
MyList.Add(Button2);
Etc...

You can then go through the list and set each buttons event handler to the same event.
E.g.
for i := 0 to MyList.Count - 1 do
  TButton(MyList[i]).OnClick := MyClickEvent;

Cheers,
JB
Yo,
you could also use the components/controls property of the owner/parent component. If you e.g. arrange all buttons on a TPanel, use its controls property array to walk through all buttons. Assign the event handler at run-time like JimBob said. To filter the button that fired the event in the handler, use

procedure TForm1.MyClickEvent(Sender: TObject);
begin
  if Sender is TButton then
   begin
     if TButton(Sender).Caption = // whatever, or use its tag property
   end;
end;

Slash/d003303
ASKER CERTIFIED SOLUTION
Avatar of rickpet
rickpet

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
rickpet,
thx to re-fomulate my comment to your answer.
d003303 Had nothing to do with your answer...I was typing up code...never saw your comment...

Rick