Mega Code Archive

 
Categories / Delphi / Examples
 

Create a control by name

How to create a control when only given the classname of the control. First the class needs to be registered, this is done in the initialization section. RegisterClasses([TEdit]); Then we find the class object (classes are objects too) for the control, and check that it is in fact a TControl. CClass := FindClass('TEdit'); Assert(CClass <> nil); Assert(CClass.InheritsFrom(TControl)); Finally we cast the class as a TControlClass (in order to call the correct constructor) and call Create. C := TControl(TControlClass(CClass).Create(Self)); The full code is below. function CreateControlByClassName(const AClassName: string; AOwner: TComponent): TControl; var CClass: TClass; begin CClass := FindClass(AClassName); Assert(CClass <> nil); Assert(CClass.InheritsFrom(TControl)); Result := TControl(TControlClass(CClass).Create(AOwner)); end; initialization RegisterClasses([TEdit]); end.