Delphi .NET (2) Database (71) Delphi IDE (90) Network (39) Printing (3) Strings (12) VCL (83) Windows with Delphi (280)
Exchange Links About this site Links to us 
|
How to create a datamodule/ form at runtime from a DFM
1 comments. Current rating: (1 votes). Leave comments and/ or rate it.
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]); NewComponent := Reader.ReadRootComponent(nil)
finally
Reader.Free;
Stream.Free
end;
end. | |  | |  | You don't like the formatting? Check out SourceCoder then!
Comments:
|