Link to home
Create AccountLog in
Avatar of pr2501
pr2501

asked on

To use componentcount



i  can't use next :
for J := 0 to ComponentCount - 1 do
      if Components[J] is TLabel then

Can you integrate it in code below?
I need number of Tshapes.
procedure TForm1.checkshapeNoFree();
   var
   i,ComponentCount :integer;
begin
      FShapeCount:=1;
           for I := 0 to 100 do  begin
              try
                if findcomponent ('shape'+inttostr(FShapeCount)) <> nil then begin
                 Form1.Edit1.text:=inttostr(FShapeCount);
                 inc(FShapeCount);
                end;
              except
                   exit;
              end;
           end;
end;

Open in new window

Avatar of jimyX
jimyX

You can loop through the entire components on a form and if it is a TShape then update the counter:

Function GetTShapeCount(): integer;
var
  i, num : Integer;
begin
  num := 0;
  for i := 0 to Form1.ComponentCount-1 do
    begin
      if Form1.Components[i] is TShape then
        inc(num);
    end;
  result := num;
end;


procedure TForm1.Button1Click(Sender: TObject);
begin
  showmessage(inttostr(GetTShapeCount()));
end;

Open in new window

procedure TForm1.checkshapeNoFree();
var FShapeCount :integer;
begin
          for FShapeCount := 0 to 100 do  begin
              try
                 if findcomponent ('shape'+inttostr(FShapeCount)) <> nil then
                 Form1.Edit1.text:=inttostr(FShapeCount);
              except
              exit;
              end;
           end;
end;
ASKER CERTIFIED SOLUTION
Avatar of jimyX
jimyX

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
A suggestion:

Just noticed in your other question that you use "FShapeCount" as global variable with applying the above function no need to make "FShapeCount" global variable all you have to do is to get benefit of the returned value of the function:

Constructor TMyObject.Create(aParent:TWinControl);  //create
begin
_Shape:=TShape.Create(aParent);
  With _Shape do
    begin
      Parent:=aParent;
      Name := 'Shape' + IntToStr(Form1.checkshapeNoFree());
      Tag:=Integer(Self);
      hint:= _Shape.Name;
      _Shape.ShowHint := True;
      Brush.Color := clwhite;
      onMouseDown := Form1.ShapeMouseDown;
      onMouseMove := Form1.ShapeMouseMove;
     //onMouseUp := Form2.ShapeMouseUp;
    Width := 10;
   Height := 10;
    end;
 _Label:=TLabel.Create(aParent);
 With _Label do
  begin
   Parent:=aParent;
   Tag:=Integer(Self);
   Width := 10; //
   Height := 10;
   Name := 'Label' + IntToStr(Form1.checkshapeNoFree());
   Caption:= _Label.Name;
  end;    
  SetPosition(10,10);
end;

Open in new window

Avatar of pr2501

ASKER

thank you
fwiw, it would be a lot better to have your own component manage all the shapes and labels,
including saving and loading and not set the form as owner

i'll show a sample next year ... got to celebrate now ...
happy end