I'm having problem with object(s) created while my program is running
First I create n objects (let's say that n := 3)
for i:=0 to n-1 do
begin
With TGauge.Create(Form1) do
begin
Parent := Form1; // this is important
Left := 20; // X coordinate
Top := 20+i*45; // Y coordinate
Width := 250;
Height := 20;
Kind := gkHorizontalBar;
Name := 'MyGauge'+IntToStr(i);
//....
Visible := True;
end;
end;
These 3 objects are created and visible in the form. Now I want to alter its' property, but whenever I try to access these created object I only get
EAccessViolation
for example when I try to get name of one object
g := Form1.FindComponent('MyGauge0') as TGauge;
Form1.Label1.Caption:=g.Name;
Your code is failing because FindComponent
returns nil
. That's because the Form1
object does not own a component with that name. Quite why that is so is hard to tell from here.
However, using name lookup is the wrong way to solve your problem. Don't use names to refer to components. Hold their references in an array.
var
Gauges: array of TGauge;
....
SetLength(Gauges, N);
for I := 0 to N-1 do
begin
Gauges[i] := TGauge.Create(Form1);
....
end;
Then you can refer to the controls using that array.
I would also comment that it is odd that you are referring to the Form1
global object. It would likely be better to do this inside the TForm1
class and so be able to use the implicit Self
instance.