Recent

Author Topic: How to delete a dynamically created component (solved)  (Read 1230 times)

zx2390

  • Newbie
  • Posts: 2
How to delete a dynamically created component (solved)
« on: August 26, 2020, 10:07:48 am »
Hello, I'm relatively new in using pascal. School requires me to do a project and I want to use a dynamically created component(TEdit in this case). But I want it to be deleted/removed in some conditions, I have tried freeandnil but it didn't work, how can I do it?

Code: Pascal  [Select][+][-]
  1. procedure TForm2.ComboBox1Change(Sender: TObject);
  2.  var
  3.    devEdit: TEdit;
  4. begin
  5.  case ComboBox1.ItemIndex of
  6.     0: FreeAndNil(devEdit);
  7.     1: FreeAndNil(devEdit);
  8.     2: FreeAndNil(devEdit);
  9.     3: FreeAndNil(devEdit);
  10.     4: FreeAndNil(devEdit);
  11.     5: begin
  12.         devEdit := TEdit.Create(self);
  13.         devEdit.parent := Form2;
  14.         devEdit.width := 150;
  15.         devEdit.height := 100;
  16.         devEdit.font.size := 16;
  17.         devEdit.left := 192;
  18.         devEdit.top := 40;
  19.        end;
  20.   end;
  21. end;                      

I want the TEdit to appear when Itemindex is 5 and I want it to disappear when itemindex is not 5.
Thanks for helping.
« Last Edit: August 26, 2020, 10:19:22 am by zx2390 »

wp

  • Hero Member
  • *****
  • Posts: 13207
Re: How to delete a dynamically created component
« Reply #1 on: August 26, 2020, 10:14:40 am »
The variable "varEdit" is local to the Combobox1Change procedure. This means that TForm2 cannot remember this variable after you exited the procedure. Make "varEdit" a global variable of class TForm2. I'd put it into the "private" section because normally such variables are only needed within the class. If you want to access the variable from the outside, e.g. from another form, you must put it into the "public" section.

Code: Pascal  [Select][+][-]
  1. type
  2.   TForm2 = class(TForm)
  3.     procedure Combobox1Change(Sender: TObject);
  4.   private
  5.     FDevEdit: TEdit;
  6.   end;
  7. ...
  8. procedure TForm2.Combobox2.Change(Sender: TObject);
  9. begin
  10.   if Combobox1.ItemIndex = 5 then
  11.   begin
  12.     FDevEdit := TEdit.Create(self);
  13.     ...
  14.   end else
  15.     FreeAndNil(FDevEdit);
  16. end;
« Last Edit: August 26, 2020, 10:18:09 am by wp »

zx2390

  • Newbie
  • Posts: 2
Re: How to delete a dynamically created component
« Reply #2 on: August 26, 2020, 10:18:57 am »
The variable "varEdit" is local to the Combobox1Change procedure. This means that TForm2 cannot remember this variable after you exited the procedure. Make "varEdit" a global variable of class TForm2. I'd put it into the "private" section because normally such variables are only needed within the class. If you want to access the variable from the outside, e.g. from another form, you must put it into the "public" section.

Fixed, thank you!

 

TinyPortal © 2005-2018