Search code examples
delphidelphi-10.1-berlin

Its safe clearing component?


I use this code for emptying fill in the form :

var
i: integer;

for i:=0 to componentcounts-1 do
    begin
    if component[i] is TEdit then
       (component[i] as Tedit).text:='';
   .....another component also include
    end;

but i prefer use this code outside the form, so that can be use by another form

then i create a procedure

procedure emptyForm(f:Tform)
var
   i:integer;
begin
with f do
     begin
     for i:=0 to componentcounts-1 do
         begin
         if component[i] is TEdit then
           (component[i] as Tedit).text:='';
           //.....another component also include
        end;
     end;
end;

its save do this way ?


Solution

  • It's OK I suppose, but using 'with' is a little dangerous. To see why, remember that TForm is descended from TComponent and has many of the same properties as Component[i] leading to potential confusion and errors. I prefer the following

    procedure emptyForm(f:Tform);
    var
       i:integer;
       iComponent : TComponent;
    begin
         for i:=0 to f.componentcount-1 do
         begin
             iComponent := f.Components[ I ];
             if iComponent is TEdit then
             begin
               (iComponent as Tedit).text:='';
             end;
               //.....another component also include
         end;
    end;