Page 1 of 1

Create a component with a given ClassName value at runtime?

PostPosted: July 20th, 2004, 6:18 am
by hadipardis
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

PostPosted: July 20th, 2004, 9:28 am
by Kambiz
Look at the FindClass definition at Delphi's help.

PostPosted: July 20th, 2004, 3:17 pm
by hadipardis
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?????

PostPosted: November 15th, 2004, 3:03 am
by julian
"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;