Delphi Pages Forums  

Go Back   Delphi Pages Forums > Delphi Forum > General

Lost Password?

Reply
 
Thread Tools Display Modes
  #1  
Old 01-10-2001, 02:31 AM
TheDuke TheDuke is offline
Senior Member
 
Join Date: Jan 2001
Posts: 269
Default How to add a TListBox to a form at runtime?

Hello, consider this code:
procedure TForm1.Button1Click(Sender: TObject);
var FRec:TSearchrec;
ListBox1:TListBox;
begin
listbox1:=Tlistbox.Create(Self);
listbox1.Visible:=false;
listbox1.Sorted:=True;
ris:=findfirst('c:\*.*',faAnyFile,FRec);
while ris=0 do begin
listbox1.Items.Add(frec.name);
ris:=findnext(FRec);
end;
findclose(Frec);
listbox1.destroy;
end;

When i execute it, i get an EInvalidOperation exception with message "Control has no parent window".
What is wrong? i tried using FORM1 instead of the Self pointer, but still got the same error.
Reply With Quote
  #2  
Old 01-10-2001, 03:26 AM
pascal.enz pascal.enz is offline
Member
 
Join Date: Jan 2001
Posts: 73
Default RE: How to add a TListBox to a form at runtime?

To create a control at runtime, you must set the parent property of the control. So you have to add the command listbox1.parent := self;

P.S. You should never destroy a component with the "destroy" command. Use "free" instead! And to be sure that all allocated memory is released after an possible excepten, you should use a try...finally structure.

The correct code should look like this.

procedure TForm1.Button1Click(Sender: TObject);
var FRec:TSearchrec;
ListBox1:TListBox;
begin
listbox1:=Tlistbox.Create(Self);
try
listbox1.Visible:=false;
listbox1.Sorted:=True;
listbox1.Parent := Self;
ris:=findfirst('c:\*.*',faAnyFile,FRec);
while ris=0 do begin
listbox1.Items.Add(frec.name);
ris:=findnext(FRec);
end;
findclose(Frec);
finally
listbox1.free;
end;
end;
Reply With Quote
  #3  
Old 01-10-2001, 04:05 AM
Lapince Lapince is offline
Senior Member
 
Join Date: Jan 2001
Posts: 163
Default RE: How to add a TListBox to a form at runtime?

Just add "listbox1.parent:=form1" after "create"...
Reply With Quote
Reply

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is On

Forum Jump


All times are GMT. The time now is 10:44 AM.


Powered by vBulletin® Version 3.8.8
Copyright ©2000 - 2018, vBulletin Solutions, Inc.