Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting all components of a certain class on a form (Delphi)

This is probably a stupid question, but my brain is just cooked enough I think I'm going to use one of my "lifelines" to see if I can get some help from my stack overflow friends. ;)

I need to delete all occurrences of a particular component type on my main form (some of them are inside panels or tabsheets, but all on and owned by the same form). Here's what I have now:

for i := 0 to frmMain.ComponentCount - 1 do  
  begin  
    if frmMain.Components[i] is TMyClass then frmMain.Components[i].Destroy;  
  end;    

The problem is (and I knew it would be before I compiled it) that once I destroy the component, the form's component list re-indexes and I end up out of bounds.

What's the best way to solve this? I thought about adding the "found" components to a standalone array, and then walk through that after this loop to delete them, which I think will work.... but is that the best approach?

TIA


UPDATE:

You guys rock. Thanks. : )

like image 478
Jamo Avatar asked Feb 11 '09 22:02

Jamo


2 Answers

You're nearly right. Your loop should look like

for i := frmMain.ComponentCount - 1 downto 0 do
begin
  if frmMain.Components[i] is TMyClass then
    frmMain.Components[i].Free;
end;

This way the call to the function "frmMain.ComponentCount" gets done at the beginning and not again.

You should also call Free as above, not Destroy - I can't remember why at the moment. Bri

like image 138
Brian Frost Avatar answered Nov 07 '22 14:11

Brian Frost


Start at the top and work backwards.

viz:

for i := frmMain.ComponentCount - 1 downto 0 do
begin
  if frmMain.Components[i] is TMyClass then frmMain.Components[i].Free;
end; 

Call free instead of Destroy. Free calls Destroy after checking for a valid reference.

like image 10
jrodenhi Avatar answered Nov 07 '22 16:11

jrodenhi