procedure TForm2.Button1Click(Sender: TObject);
// here I do create a new type that I need to store found TLabel object in
type
TLabels = array of TLabel;
var
// x, y, z are needed as Counters (x = a Form, y = an Object, z = array entries)
x, y, z: Integer;
// this is the actual array that holds the found objects of type TLabel
arr: TLabels;
begin
// initialize empty array
arr := nil;
SetLength(arr, 0);
// x is my counter for the root of everything, my Pred() can also be written like
// for x := 0 to Application.ComponentCount -1 do ...but I do hate to write -1 or +1
for x := 0 to Pred(Application.ComponentCount) do
// Application.Components[x] is the current object I am into, in that case I want to dig deeper into a TForm what has inside its name "Form1" written (case sensitive!)
if (Pos('Form1', Application.Components[x].Name) > 0) then
// y is now the root of the found form where I am digging and digging
// again using Pred to avoid writing "-1"
// translated this line means:
// for y := 0 to Form1.ComponentCount -1 do
// but with this kind of technique we have to write it like that:
for y := 0 to Pred((Application.Components[x] as TForm).ComponentCount) do
// remember, x = Form1 and y = all objects on that
// next line eliminate everything that is not a TLabel
if (((Application.Components[x] as TForm).Components[y] is TLabel) and
// and only keep a TLabel when it's Tag value is "666"
(((Application.Components[x] as TForm).Components[y] as TLabel).Tag = 666)) then
begin
// z keeps track of my array, it represent current amount of entries
// so first get current number of entries:
z := Length(arr);
// increase the array by one
// you can also write:
// SetLength(arr, z + 1);
// but as told, I do hate write -1 or +1
SetLength(arr, Succ(z));
// here we add the found TLabel into my array
// remember, x = Form1, y = the object
arr[z] := ((Application.Components[x] as TForm).Components[y] as TLabel);
end;
// when my array is bigger than 0
if (Length(arr) > 0) then
begin
// generate a random number based on the number of possible entries
x := Random(Length(arr));
// patch/overwrite the caption for one of the found possible TLabels
arr[x].Caption := IntToStr(Succ(x));
// the following is not needed, but I do it anyway
SetLength(arr, 0);
arr := nil;
end;
end;