Board index » delphi » Removing Children from Parent Component

Removing Children from Parent Component

The following code is supposed to remove all components with assigned Tags
from a TTabSheet but keeps giving me a "list out of bounds" error.  I'm
pretty sure the reason this is happening is the ComponentCount is updating
on the fly and I have the "old" count.  What needs to be done to the code to
make it work properly.

Thanks in advance,

...Wade...

procedure TdFirstGuess.RemoveSegments(Sender : TObject);
// I pass in a pointer to a TTabSheet
var
  I : Integer;
begin
  for I := 0 to ComponentCount -1 do
    if ((Components[I].Tag > 0) and
       (TControl(Components[I]).Parent = Sender)) then begin
         Components[I].Free;
         TControl(Components[I]).Parent := nil;
         end;
end;

 

Re:Removing Children from Parent Component


In message <863ruc$f...@bornews.borland.com>, Thomas W. Earle stated:

Quote
> for I := 0 to ComponentCount -1 do

for I := ComponentCount - 1 downto 0 do...

===
Regards
Ralph (TeamB)
===

Re:Removing Children from Parent Component


Ralph,

Thanks for the help but for some unknown reason I am still getting the list
out of bounds error.  Perhaps I am doing things in a dangerous way or
incorrectly.  Any suggestions would be greatly appreciated.

Quote

> for I := ComponentCount - 1 downto 0 do...

Re:Removing Children from Parent Component


In message <8642cg$f...@bornews.borland.com>, Thomas W. Earle stated:
Quote
> Thanks for the help but for some unknown reason I am still getting the list
> out of bounds error.  Perhaps I am doing things in a dangerous way or
> incorrectly.  Any suggestions would be greatly appreciated.

> Components[I].Free;
>          TControl(Components[I]).Parent := nil;

I didn't notice the above sequence when I read your code originally. You
can't do anything to the properties of a component that has just been freed.

===
Regards
Ralph (TeamB)
===

Re:Removing Children from Parent Component


Ralph,

Thanks for all your help.  I slept over it last night and figured that was
the problem.  Sure is hard to find those subtle bugs.  I would have thought
I would have got an access violation on that one rather than a list out of
bounds error.

...Wade...

Re:Removing Children from Parent Component


In message <86529q$g...@bornews.borland.com>, Thomas W. Earle stated:
Quote
> I would have thought
> I would have got an access violation on that one rather than a list
out of
> bounds error.

Wade,

The index reference executed (probably on your last Free) before you
had a chance to do the damage that might have resulted in an AV.

===
Regards
Ralph (TeamB)
===

Other Threads