Do not tell me whether you can do this:

TImage(Form1.Controls[2]).Picture := nil; 

I checked in advance by the name of the control that it is Timage ;

or you can do it this way:

 TImage(FindComponent('Image1')).Picture := nil; 

Or is it still possible to do this?

 With TImage(Form1.Controls[2])do begin .... .... end; 
  • one
    You can do it (all 3 options), but for each of the options you will be kicked in production. And what is the goal? - Kromster

3 answers 3

It seems to me that addressing by the index is not very good, because the index says nothing about the intention of your code. Well, the index can change if you (or your follower in the project) add more controls. It is better to refer to the control by name.

By the way, I would have invented a more meaningful name than Image1 : in the middle of the night you wouldn’t say how Image1 differs from Image2 , but exactly Image_UserAvatar from Image_CountryFlag .

WPF has the ability to address controls in the window by name (for your case, it would be Form1.Image1 ), and in this case, the caste is not needed - if there is such a possibility in Delphi, it is better to use it.

  • Well, thanks of course about the name, but I just gave an example, they are called clearer (at least for me) Regarding the index, I check the given control for the name match in advance. Well, I didn’t seem to have said for nothing that I dynamically create controls, respectively, can’t apply Form1.Image1 - Jericho
  • one
    @Jericho: And if you add something dynamically, then maybe it makes sense to memorize in a special variable or array? That eats; for example, if you add 100 pictures, then just start a field - an array of pictures, and instead of crawling into the child-elements of Form1 just take them from the array. Immediately there will be typing, and the compiler will catch errors. - VladD 2:49
  • In addition, you can use generics, for example TObjectList <T>, after clearing the list - all objects are deleted. This is depending on the needs of the author. - androschuk

Use is and as expressions.


 for i:= 0 to Form1.ControlsCount - 1 do begin if (Form1.Controls[I] is TImage) then (Form1.Controls[I] as TImage).Picture := nil; end; 

If you'll dynamically create a TImage list, write them down TList <T> TObjectList <T>. Then the search can be carried out on the current list.

    Here it is possible

     With Form1.Controls[2]do begin ... ... ... end; 
    • 2
      Um, if you write like you, it will not inherit the properties of a TImage. - Jericho
    • Maybe I'm wrong and you're right, now I can not check there is no computer at hand. - Jericho