DelphiFAQ Home Search:

How to create a datamodule/ form at runtime from a DFM


comments1 comments. Current rating: 5 stars (1 votes). Leave comments and/ or rate it.


I want to read a DataModule.dfm and create an instance of it into my application.


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;

  Stream: TFileStream;
  Reader: TReader;
  NewComponent: TComponent;

  Stream := TFileStream.Create(Filename, fmOpenRead);
  Reader := TReader.Create(Stream, 4096);
    RegisterClasses([TForm, TEdit]); // all class types you need in the DFM
    NewComponent := Reader.ReadRootComponent(nil)
You don't like the formatting? Check out SourceCoder then!
Content-type: text/html


2006-03-04, 15:24:42
anonymous from Turkey  



NEW: Optional: Register   Login
Email address (not necessary):

Rate as
Hide my email when showing my comment.
Please notify me once a day about new comments on this topic.
Please provide a valid email address if you select this option, or post under a registered account.

Show city and country
Show country only
Hide my location
You can mark text as 'quoted' by putting [quote] .. [/quote] around it.
Please type in the code:

Please do not post inappropriate pictures. Inappropriate pictures include pictures of minors and nudity.
The owner of this web site reserves the right to delete such material.

photo Add a picture: