Recent

Author Topic: Access Components as an array  (Read 6742 times)

Arbee

  • Full Member
  • ***
  • Posts: 223
Access Components as an array
« on: December 16, 2010, 03:15:06 pm »
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?
1.0/2.6.0  XP SP3 & OS X 10.6.8

Imants

  • Full Member
  • ***
  • Posts: 196
Re: Access Components as an array
« Reply #1 on: December 16, 2010, 03:26:53 pm »
Try something like this:

Code: [Select]
Procedure SetCmpValues(ACmpOwner: TComponent);
Begin
  for i := 0 to Aowner.ComponentsCount - 1 do
  Begin
    FCmp := ACmpOwner.FindComponent('Edit' + IntToStr(i + 1));
    ...
  end;
end;

Arbee

  • Full Member
  • ***
  • Posts: 223
Re: Access Components as an array
« Reply #2 on: December 17, 2010, 11:15:17 pm »
Yep, works.  I used this suggestion in a property

Code: [Select]
property AmountEdit[index: word] : string read getAmount write SetAmount;

And the getter then contains - for instance :

Code: [Select]
function TSomeClass.GetAmount(index : word) : String;
begin
   Result := (self.FindComponent('RateEdit'+IntToStr(index)) as TMaskEdit).text;
end;

So I can then simply use the array property.

Thanks for this.
1.0/2.6.0  XP SP3 & OS X 10.6.8

 

TinyPortal © 2005-2018