Delete Tedit created at runtime

Asked

Viewed 430 times

0

At the click of the button I create some Edits... So far everything works normally, but when I try to exclude edits created by clicking another button, not all are deleted.

Ex. I created 10 fields edits, when I click to delete all at once, only 5 are deleted. Follow the codes (inclusion and exclusion respectively):

for x := 0 to (NumReg -1) do
begin
  ArrayEdit[x] := TEdit.Create(Self);
  ArrayEdit[x].Parent := Self;
  ArrayEdit[x].Name := 'edtPreco'+ IntToStr(x+1);
  ArrayEdit[x].Left := 265;
  ArrayEdit[x].Top := 300 + x * 25;
end;

var Component: TComponent; 
begin 
  for Component in Self do 
    if Component is TEdit then
      TEdit(Component).Free;
end;

2 answers

2

procedure TForm2.Button1Click(Sender: TObject);
var
  i: Integer;
begin
  for i := ComponentCount - 1 downto 0 do
  begin
    If (Components[i] is TEdit) then
      TEdit(Components[i]).Destroy;
  end;
end;

0

Try this:

while (Form1.ComponentCount > 1) do 
begin
  if (Form1.Components[0] is TEdit) then
    TEdit(Form1.Components[0]).Free;
end;
  • If the guy has one TButton in the Form1, will already enter an infinite loop. And another question is that this way, will not destroy the last TEdit, for the ComponentCount will be = 1, and not > 1

  • guy tested here fast this code and with 0 gave access Violation only with 1 worked and another if the component is Edit that will delete

  • I saw that in your code you use Destroy was with a doubt about that, some time was with problem of memory Leak using free, I started to use Destroy and solved, would you explain to me the difference between the two? I searched a lot on the internet but found no answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.