Author: Tomas Rutkauskas
My code looks something like this: ... if CheckBox(var).checked = True then ...
where (var) is a counter in a for loop. Is the number of checkboxes not known when
coding , ie created only at run time?
Answer:
When in design mode, you really should know how many checkboxes are on a given
form. When the App is running, use Delphi's Run Time Type Information (RTTI). For a
given form, try the following code snippet:
1 var2 i: Integer
3 begin4 for i := 0 to ComponentCount - 1 do5 if Components[i] is TCheckBox then6 (Components[i] as TCheckBox).Checked then7 begin8 {... insert your code here ...}9 end;
10 end;
11 12 //In addition, the following code is a valid statement in Delphi:13 14 if Components[i] = CheckBox5 then DoSomething;
Also, each component in Delphi has a Published Property called 'Tag', you can use
this to your advantage by setting the Tag to some non-zero number at design time,
then using it at runtime, ie:
15 var16 i: Integer
17 begin18 for i := 0 to ComponentCount - 1 do19 if Components[i] is TCheckBox then20 with (Components[i] as TCheckBox) do21 case Tag of22 1: if Checked then23 DoSomethingOnBox1;
24 2: if Checked then25 DoSomethingOnBox2;
26 {... etc ...}27 end;
28 end;