Destroying Tedits at runtime

1

I have an application that creates TEdits from 1 to 15 I would like them to disappear, but when the person clicks the button to create them they come back ..

They were created as follows:

ArrayEdit[x] := TEdit.Create(Self);
ArrayEdit[x].Parent:= Self;
ArrayEdit[x].Left := 100 + x * 50;
ArrayEdit[x].Top := 124;
ArrayEdit[x].Width := 41;
ArrayEdit[x].Height :=24;
ArrayEdit[x].Name := 'edit'+ inttostr(x+20);

And I'm destroying them as follows:

 for i := ComponentCount - 1 downto 0 do
    begin
      If (Components[i] is tedit) then
        Tedit(Components[i]).Destroy;
    end;

The problem is as follows, it gives an Access Violation error and also seeu destroy the edits will I have to close the application to use them again, any ideas?

    
asked by anonymous 06.10.2015 / 14:29

2 answers

2

Some comments:

  • Do not run Destroy directly, prefer to use Free , which runs Destroy only after checking if the component is actually allocated.

  • What do you call "fade away" is actually destroying the component? Would it not be enough to make them invisible?

To make them invisible, you just have to do:

for i := ComponentCount - 1 downto 0 do
begin
  If (Components[i] is tedit) then
    Tedit(Components[i]).Visible:= false;
end;

And to make them visible again, it would just do

for i := ComponentCount - 1 downto 0 do
begin
  If (Components[i] is tedit) then
    Tedit(Components[i]).Visible:= true;
end;
    
08.10.2015 / 20:20
1

With this code here (which uses the code you passed), everything is ok.

unit Unit2;

interface

uses
  Winapi.Windows,
  Winapi.Messages,
  System.SysUtils,
  System.Variants,
  System.Classes,
  Vcl.Graphics,
  Vcl.Controls,
  Vcl.Forms,
  Vcl.Dialogs,
  Vcl.StdCtrls;

type
  TForm2 = class(TForm)
    btn1: TButton;
    btn2: TButton;
    procedure FormCreate(Sender: TObject);
    procedure btn2Click(Sender: TObject);
    procedure btn1Click(Sender: TObject);
  private
    procedure criarEdits;
  public

  end;

var
  Form2: TForm2;

implementation

{$R *.dfm}

procedure TForm2.btn1Click(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;

procedure TForm2.btn2Click(Sender: TObject);
begin
    criarEdits;
end;

procedure TForm2.criarEdits;
var
  i : Integer;
  arrayEdit : array[1..15] of TEdit;
begin
  for i := 1 to 15 do
  begin
    ArrayEdit[i] := TEdit.Create(Self);
    ArrayEdit[i].Parent:= Self;
    ArrayEdit[i].Left := 100 + i * 50;
    ArrayEdit[i].Top := 124;
    ArrayEdit[i].Width := 41;
    ArrayEdit[i].Height :=24;
    ArrayEdit[i].Name := 'edit'+ inttostr(i+20);
  end;
end;

end.
    
06.10.2015 / 15:46