Forum > LCL
Access Components as an array
(1/1)
Arbee:
Lately I've been developing quite a few applications where there is a range of similar components on screen. For instance 12 TEdits for entering an amount for each month of the year. So after dropping the components on the form you will have fields like AmountEdit1, AmountEdit2, AmountEdit3 and so on.
More often than not it is convenient to be able to access them as an array. So I additionally define a
AmountEdit: array[1..12] of TEdit;
And in the FormCreate make these point to the real fields:
AmountEdit[1] := AmountEdit1;
AmountEdit[2] := AmountEdit2;
AmountEdit[3] := AmountEdit3;
: :
AmountEdit[12] := AmountEdit12;
A bit cumbersome in the beginning, but once done the fields can be conveniently accessed via the array (like loading them in a for-loop)
My question. Is there actually a more direct way of doing this (other than entering the amounts in a grid)? Can you somehow name the fields on the screen as array entries in some way?
Imants:
Try something like this:
--- Code: ---Procedure SetCmpValues(ACmpOwner: TComponent);
Begin
for i := 0 to Aowner.ComponentsCount - 1 do
Begin
FCmp := ACmpOwner.FindComponent('Edit' + IntToStr(i + 1));
...
end;
end;
--- End code ---
Arbee:
Yep, works. I used this suggestion in a property
--- Code: ---property AmountEdit[index: word] : string read getAmount write SetAmount;
--- End code ---
And the getter then contains - for instance :
--- Code: ---function TSomeClass.GetAmount(index : word) : String;
begin
Result := (self.FindComponent('RateEdit'+IntToStr(index)) as TMaskEdit).text;
end;
--- End code ---
So I can then simply use the array property.
Thanks for this.
Navigation
[0] Message Index