Mega Code Archive

 
Categories / Delphi / Examples
 

How to create a datamodule- form at runtime from a dfm

Problem: I want to read a DataModule.dfm and create an instance of it into my application. Answer: You generally cannot this (easily). A form or datamodule is much more than the resource file. The resource only contains the saved properties of the objects you placed at designtime on the form/DM, it does not contain any of the form/DM classes code, for example constructors won't get executed, and without that the stuff in the resource file is usually fairly useless. You *can* load the resource, however you have to first call RegisterClass for each and every object class used in the resource, otherwise the load will fail since the stream code will be unable to create the objects contained in the stream. This is not necessary when you create a proper instance of the saved form/Dm class, since the class itself contained the info the streaming code needs. Look at the following example. program P; var Stream: TFileStream; Reader: TReader; NewComponent: TComponent; begin Stream := TFileStream.Create(Filename, fmOpenRead); Reader := TReader.Create(Stream, 4096); try RegisterClasses([TForm, TEdit]); // all class types you need in the DFM NewComponent := Reader.ReadRootComponent(nil) finally Reader.Free; Stream.Free end; end.