Home > Software design >  how to use a private datamodule vs the global instance
how to use a private datamodule vs the global instance

Time:04-19

I have a datamodule for my frame, which uses a global instance.(dmData) The data components are linked to the datasources on the dmData instance

now I want to use a datamodule instance that is private to a frame, because I want to have multiple instances of the form which contains the frame showing at the same time.

I can't figure out how to make that happen, either in code or in designing.

in the frame, I am creating the datamodule as dmLocalData := tdmData.Create(self), but in design I don't have the option to link dmLocalData, only the option to link to dmData(so all my data controls are blank (except for that ONE that has a local datasource that gets set in code)

I mean, in code, I could manually go through each component one by one and change the datasource, but thinking there really has to be a better way, the maintenance on that would be pretty much horrendous.

Any ideas about a better way?

CodePudding user response:

Actually there is a way to avoid hand-wiring the controls for a dynamically created datamodule. In short - override the datamodules CreateNew constructor like this:

constructor TMainDM.CreateNew(AOwner: TComponent; Dummy: Integer);
begin
  Dummy := -1;
  inherited;
end;

This avoids that multiple instances of the datamodule get different names and thus the references are resolved as expected. As the datamodules are private to the frame anyway, there is no need for them to have globally unique names.

A much longer and more detailed explanation can be found in these two articles, which use a quite similar task as an example:

Tweaking DFM Loading (update)

Tweaking DFM Loading

  • Related