1

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; 
4
  • 1
    Better store their references into an array, or a list like collection. Commented Jan 11, 2015 at 14:39
  • 1
    For n=3 you have 3 objects, not 4. Commented Jan 11, 2015 at 14:42
  • @Inspired thaks for notice. Just a misspell Commented Jan 11, 2015 at 15:39
  • "this is important" I would presume all of your code is important :-) Commented Jan 11, 2015 at 18:11

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.