Dynamically identify checkboxes (Views: 30)
Problem/Question/Abstract: 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: var i: Integer begin for i := 0 to ComponentCount - 1 do if Components[i] is TCheckBox then (Components[i] as TCheckBox).Checked then begin {... insert your code here ...} end; end; In addition, the following code is a valid statement in Delphi: 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: var i: Integer begin for i := 0 to ComponentCount - 1 do if Components[i] is TCheckBox then with (Components[i] as TCheckBox) do case Tag of 1: if Checked then DoSomethingOnBox1; 2: if Checked then DoSomethingOnBox2; {... etc ...} end; end; |