Delphi - Removing running generated buttons from TPanel

I have several TPanels that are filled with buttons at runtime. However, the code below, which I use to release buttons from my parent panels, sometimes generates access violation errors.

procedure TfrmTakeOrder.FreeItemButtons(buttons : array of TButton); var cnt,i : integer; begin for i := 0 to gridLayoutItems.ControlCount - 1 do begin buttons[i].Free; buttons[i] := nil; end; end; 

Is there a better way to do this? Please keep in mind that other panels have buttons, and I would like to have a β€œlocalized” release of buttons that combine with other panels.

+4
source share
6 answers

It seems to me that you are trying to remove all buttons from TPanel, and this panel contains only buttons.

Try the following:

 while gridLayoutItems.ControlCount > 0 do gridLayoutItems.Controls[0].Free; 
+7
source

If:

  • the panel has only buttons and
  • Your array has all the buttons on several panels.

Then use:

 var I: Integer; Button: TControl; begin for I := GridLayoutItems.ControlCount - 1 downto 0 do begin Button := GridLayoutItems.Controls[I]; Button.Free; { Find the index of Button in the Buttons array }; { Erase that item from the array }; end; end; 

But in this case it is much more convenient to have a TList for buttons instead of an array, because then the code becomes:

 var I: Integer; Button: TControl; begin for I := GridLayoutItems.ControlCount - 1 downto 0 do begin Button := GridLayoutItems.Controls[I]; Button.Free; Buttons.Remove(Button); end; end; 
+3
source

Maybe it is better to use Length(buttons) - 1 instead of gridLayoutItems.ControlCount - 1 , which may be different.

+1
source

You have to adjust the boundaries of your for loop, like other answers. One more thing:

How do you create buttons? If you create buttons with an owner, i.e.

 buttons [i] := TButton.Create (Panel); 

then you should not release them manually. The owner will take care of this. In this case, just use

 buttons [i] := TButton.Create (nil); 
+1
source

Yes. Use for i := Low(buttons) to high(Buttons) do

0
source

In later versions of Delphi (e.g. XE5), Free no longer exists. I solved the problem using Destroy instead of Free.

0
source

All Articles