Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an array of controls?

Tags:

delphi

I have to create an array and place all controls there in order to access them.Here's a short example:

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Button2: TButton;
    Button3: TButton;
    const Test:Array[0..2] of TButton = (Button1,Button2,Button3);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

end.

Undeclarated idenitifier 'Button1' at the line where I declarated my array.But it's declarated three lines above.

Where's the problem,how to put all controls in an array?

EDIT:

Thank you for your answers,but I've got problems:

 var TestA:TObjectList<TButton>;

 var index:TComponent;
 begin
 TestA := TObjectList<TButton>.Create(false);
   for index in Form7 do
     if pos(index.name, 'Button') = 1 then
       TestA.add(TButton(index));

 TestA[0].Caption := 'Test'; //Exception out of range.
like image 707
Ivan Prodanov Avatar asked Dec 06 '25 17:12

Ivan Prodanov


1 Answers

Ben's right. You can't set up a control array in the form designer. But if you have 110 images, for this specific case you can put them into a TImageList component and treat its collection of images as an array.

If you've got a bunch of more normal controls, like buttons, you'll have to create an array and load them into it in code. There are two ways to do this. The simple way, for small arrays at least, is Ben's answer. For large control sets, or ones that change frequently, (where your design is not finished, for example,) as long as you make sure to give them all serial names (Button1, Button2, Button3...), you can try something like this:

var
  index: TComponent;
  list: TObjectList;
begin
  list := TObjectList.Create(false); //DO NOT take ownership
  for index in frmMyForm do
    if pos('Button', index.name) = 1 then
      list.add(index);
   //do more stuff once the list is built
end; 

(Use a TObjectList<TComponent>, or something even more specific, if you're using D2009.) Build the list, based on the code above, then write a sorting function callback that will sort them based on name and use it to sort the list, and you've got your "array."

like image 67
Mason Wheeler Avatar answered Dec 08 '25 21:12

Mason Wheeler