Create a component with a given ClassName value at runtime?

Please discuss general Delphi programming topics here.

Create a component with a given ClassName value at runtime?

Postby hadipardis » July 20th, 2004, 6:18 am

Hi
The problem is:I defined var s:string
Now If I set s:='TButton' then I want to create a TButton instance and
if I set s:='TEdit' then I want to create a new TEdit instance and so on.
Note that s can get many different values dynamically at runtime,so I
dont want to use any IF or CASE statement.Is there any way to overcome
this problem?If your answer is true please give a practical example!

Thanks
hadipardis
Junior Member
Junior Member
 
Posts: 33
Joined: July 17th, 2004, 5:45 am

Postby Kambiz » July 20th, 2004, 9:28 am

Look at the FindClass definition at Delphi's help.
User avatar
Kambiz
Administrator
Administrator
 
Posts: 2429
Joined: March 7th, 2003, 7:10 pm

Postby hadipardis » July 20th, 2004, 3:17 pm

Thanks.
I use this code to show a button on the form:

var
DynamicComponent: TComponent;
CompClass: TComponentClass;
begin
RegisterClasses([TButton, TBitmap, TMetafile]);
CompClass := FindClass('TButton') as TComponentClass ;
DynamicComponent := CompClass.Create(Form1);
with dynamiccomponent do
begin
parent:=form1;
name:='ali';
left:=10;
top:=10;
visible:=true;
end;
except
ShowMessageFmt('Cannot find %s in classlist', ['ClassName']);
end;
but this code effects on the owner(Form1) and it is not true

Important:Note that I dont want use this typecasting!!!!!!!!:

with dynamiccomponent as TButton do
begin
parent:=form1;
name:='ali';
left:=10;
top:=10;
visible:=true;
end;
Now ,How I can overcome this problem?????
hadipardis
Junior Member
Junior Member
 
Posts: 33
Joined: July 17th, 2004, 5:45 am

Postby julian » November 15th, 2004, 3:03 am

"Application.CreateForm" can do

the declaration:

procedure TApplication.CreateForm(InstanceClass: TComponentClass; var Reference);
var
Instance: TComponent;
begin
Instance := TComponent(InstanceClass.NewInstance);
TComponent(Reference) := Instance;
try
Instance.Create(Self);
except
TComponent(Reference) := nil;
raise;
end;
if (FMainForm = nil) and (Instance is TForm) then
begin
TForm(Instance).HandleNeeded;
FMainForm := TForm(Instance);
end;
end;
julian
Member
Member
 
Posts: 1
Joined: November 15th, 2004, 2:02 am


Return to Delphi Programming

Who is online

Users browsing this forum: No registered users and 11 guests

cron