Destroy Tedits at runtime

Asked

Viewed 822 times

1

I have an application that creates Tedits from 1 to 15 I wish they would disappear, but when the person clicks on the button to create 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 this way:

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

The problem is this, it gives an Access Violation error and also if you destroy the edits I will have to close the application to use them again, any idea?

  • I made it here using your code and it’s okay.

2 answers

2


Some remarks:

  • Do not perform Destroy directly, prefer to use the Free, that executes the Destroy only after checking that the component is actually allocated.

  • What you call "disappearing" is actually destroying the component? It wouldn’t be enough to make them invisible?

To make them invisible would be enough to make:

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 be to do

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

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.

Browser other questions tagged

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