How to destroy all the labels on a panel, leaving other controls untouched?

Hi

I have written the following code to destroy only the labels on a panel in a form's Close event.
But when I run it, I get the error:
" Project . . . raised exception class EListError with message 'List index out of bounds(1)'. " 
This seems to occur when the control encountered is not a label.

Am I doing something stupid? Or if this method is not allowed, how do I do what I want to do?

procedure PanLabsDestroy(p:tpanel);
{   This destoys all labels on panel p  }
var
  i:integer;
  lab:tcontrol;
begin
  for i:=0 to p.controlcount-1 do
  begin
    lab:=p.controls[i];
    if lab is tlabel then lab.Destroy;
  end;
end;

Help appreciated!

tiggermark
tiggermarkAsked:
Who is Participating?
 
BlackTigerXConnect With a Mentor Commented:
try doing it in reverse order

for i:=p.ControlCount-1 downto 0 do
0
 
tiggermarkAuthor Commented:
Thanks very much. That works.

Can't think why the other doesn't though. It's all a plot!

tiggermark
0
 
BlackTigerXCommented:
because you are deleting, so the count decreases... makes sense?

after you delete one, p.ControlCount is messed up, but the original count was for example 5, and now is 4, therefor 5 doesn't exist anymore, and you get an access violation

if you go in reverse order it doesn't matter if the count changes, because you are going towards zero, not towards the original count
0
 
tiggermarkAuthor Commented:
Yes, I see.

An error occurs because one tries to use a no-longer-existing control.

Thanks.

The points are all yours!
0
 
BlackTigerXCommented:
yes... that's what access violations are all about... trying to access something that doesn't exist
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.