Advertisement

Identifier - loop use

Started by July 09, 2002 07:02 AM
0 comments, last by sanguineraven 22 years, 2 months ago
I have been programming in Delphi and come across a problem which I have often thought about and it applies not only to Delphi I have 7 labels which I''m assigning random numbers to. Currently my code looks like:
  
  label1 := random(49);
  label2 := random(49);
  label3 := random(49);
  
etc... Obviously it makes sense to have a loop. i.e
  
  for k := 1 to 7 do
  begin
    labelwhatever := random(49);
  end;
  
Now what I''m wondering is how to have label[then wotever number of loop]. I have tried several syntax variations and have checked the Borland help files What about me? What about Raven?
You could use FindComponent to find the appropriately named objects. FindComponent is a method of TComponent, which means that it will be available in your form. You could use code like the following:

type  TMyForm = class(TForm)    // lots of things go here  private    MyArray: array[0..6] of TLabel;    // other stuff goes here   

(I.e., declare your array inside the form. Get into your form's OnCreate event and put in the following code:
procedure Tyourformname.FormCreate(Sender: TObject);var  iter: Integer;begin  for iter := Low(MyArray) to High(MyArray) do    MyArray[iter] := FindComponent('Label' + IntToStr(iter+1)) as TLabel;end;   


That will fill your array up with the labels, which you can then use as you please. Of course, it's a bit shifty relying on a variable's name but whatever, it works. FindComponent returns the component with the given name, or nil if it isn't found (I believe). If you place the object on something (for example, a TPanel) then you could change the code to look like this: MyArray[iter] := Panel1.FindComponent{etc};

[edited by - Alimonster on July 9, 2002 8:25:32 AM]

[edited by - Alimonster on July 9, 2002 8:28:44 AM]

This topic is closed to new replies.

Advertisement