Link to home
Start Free TrialLog in
Avatar of Brooky
Brooky

asked on

array of labels?

ok people, i am developing an application which requires me to be referring to any one of 42 labels that i have defined. It would be extremely labourous for me to do an individual procedure to go with each label, what i need to do is write a procedure that can altar any one of the labels depending on a passed parameter. E.g instead of having to refer to label1.caption (or whatever, i could refer to label[n].caption, ok? if anyone knows how i can achive this effect then please let me know:)
Avatar of Vendi
Vendi

http://www.edgequest.com/Development/DelphiArticles.htm

This site has an article about control arrays in Delphi.  I think it is what you are looking for.  If it is, hand over the points, ha!  :)
you can use array (or TList?). to initialize it you can do next:

for i := 0 to Form1.ComponentCount - 1 do
    if Form1.Components[i] is TLabel then
  {add to your store - array, Tlist or other}

Then you can refer to it by index.
Note. if use TStringList you can store for example label.caption in Strings and label in Objects
ASKER CERTIFIED SOLUTION
Avatar of DrDelphi
DrDelphi

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
you can use array (or TList?). to initialize it you can do next:

for i := 0 to Form1.ComponentCount - 1 do
    if Form1.Components[i] is TLabel then
  {add to your store - array, Tlist or other}

Then you can refer to it by index.
Note. if use TStringList you can store for example label.caption in Strings and label in Objects
you could do something like :

procedure TForm1.Button1Click(Sender: TObject);
var
  i : integer;
n:string;
begin
n := edit1.text;
  for i := 0 to ComponentCount-1 do
    begin
      if( Components[ i ] is TLabel )
and pos(n,components[i].name))
then
      begin
        (Components[ i ] as TLabel).Caption := 'Hello';
      end;
  end;
Avatar of kretzschmar
hmm,

you can also keep the automatical given names of the labels
(Label1, Label2, Label3, Label4 ... and so on)

and use this code

Procedure TForm1.ChangeLableText(Text : String;Id : Integer);
var TheLabel : TComponent;
begin
  Try
    TheLabel := FindComponent('Label'+IntToStr(Id)); //Label4 for ex
    If (Assigned(TheLabel)) and
       (TheLabel is TLabel) then
      TLabel(TheLabel).Caption := Text;
  Except
    //an error
  end;
end;

//sample for use
procedure TForm1.Button1Click(Sender: TObject);
begin
  ChangeLableText(Edit1.Text,StrToInt(Edit2.Text));
end;

meikl ;-)
you could define them statically, as you apparently
know how many labels you have

Labels:array [1..NrOfLabels] of TLabel;

then you have easy access with:
Labels[i].caption