Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Access TComponent by number 1

Status
Not open for further replies.

EricDraven

Programmer
Jan 17, 2002
2,999
GB
Hi all,

I want to be able to access a components property by its number. For example, I have 20 images all visible := false;
I also have a random number X. What I want to do is display the TImage like so.

Image2.Visible := True;

Would be

TImage(X).Visible := True;

This doesnt work though. I have tried using,

(Components[X] as TImage).Visible := True;

however this doesnt display every possible image. Im guessing this is because there could be other components with a number in the range 1 - 20 before the images. Anybody have any ideas??? Arte Et Labore
 
Maybe something along these lines:

LImage := AForm.FindComponent('Image' + IntToStr(x));
LImage.Visible := true;

It doesn't have to be a form, any TComponent can call FindComponent(S:String):TComponent.
 
If your images are called Image1, Image2, Image3, .. Image20 then it is very easy. The function to use is FindComponent.

Here is sample function that will return the image that you want.
Code:
function GetImage ( n: integer ): TImage;
begin
  result := FindComponent ('Image' + IntToStr(n) ) as TImage;
end;
So all you need do in your main code to make image 17 visible is to code
Code:
  GetImage(17).Visible := true;

With a little extra effort you can have an indexed property and then you can use square brackets so that you could code things like
Code:
  Image[15].Visible := false;
The way to do this is to add the following line in the private section of the form containing the 20 images.
Code:
function GetImage(index: integer): TImage;
and add the following line to the public section.
Code:
property Image[index: integer]: TImage read GetImage;
and then code the GetImage function in the implementation part of your program (assuming the form is called TForm1):
Code:
function TForm1GetImage(index: integer): TImage;
begin
  result := FindComponent ('Image' + IntToStr(index) ) as TImage;
end;





 
Sorry, there is a period missing from the last function. It should read
Code:
function TForm1.GetImage(index: integer): TImage;
 
First prize goes to Towerbase. Never thought of using FindComponent but your function seems to do the job bang on the money!

Cheers Arte Et Labore
 
U could also use an array of timage

myArray = array [1..20] of TImage;

//in the code (in the create event for ex)
//use this to create your image....

//for cpt = 1 to 20.......
myArray[cpt]:=TImage.create(self);
myArray[cpt].Parent=self;

jb
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top