The dynamic form creation subject has been covered many times, but I could not find something to solve my problem, so here I am... again... :-)
My previous questions lead me to think that my application would start faster if not all forms were created on startup, but created dynamically when needed. And that is mostly true, the startup is much faster when I only have my main Form and a Datamodule created.
On button click, here is the code I use to create and free forms on demand (mostly inspired by what I found here from answers by Jerry Dodge and Craig Young, thanks to them for their assistance) :
procedure TfrmWelcome.BtKeywordsClick(Sender: TObject);
var
F_Keywords : TfrmKeywords;
begin
F_Keywords := Tfrmkeywords.Create(nil);
try
F_Keywords.ShowModal;
finally
F_Keywords.Free;
end;
end;
Again, this works fine but, on creation of frmKeywords, a main tablegrid is supposedly filled by a FDQuery that fires upon displaying the form. Of course (or I would not be here), adding
frmKeywords.FDQuery1.Open;
in the FormShow or FormCreate event ends up with an "access violation error".
So I modified my creation code and it now looks like :
procedure TfrmWelcome.BtKeywordsClick(Sender: TObject);
var
F_Keywords : TfrmKeywords;
begin
F_Keywords := Tfrmkeywords.Create(nil);
try
F_Keywords.FDQuery1.Open;
F_Keywords.ShowModal;
finally
F_Keywords.FDQuery1.Close;
F_Keywords.Free;
end;
end;
(I'm not even sure that the FDQUery1.Close
is useful in the finally block).
Great, now my Form shows up and the main datagrid is filled with data.
Problem is that, when the user clicks in the DBGrid1, the database id of the selected record is passed as a parameter to a secondary FDQuery which in return fills a secondary DBGrid with data (master data in DBgrid1, child data in DBGrid2)
This is done like :
procedure TfrmKeywords.DBGridEh1CellClick(Column: TColumnEh);
var
kwid : Integer;
begin
frmKeywords.FDQuery2.Close; //Closing secondary query
kwid := FDQuery1.FieldByName('id').AsInteger; //Assigning kw_id according to selected row
frmKeywords.FDQuery2.ParamByName('kw_id').AsInteger := kwid; //Linking query2 parameter to kwid
frmKeywords.FDQuery2.Open; //Reopening query2 to display assets
end;
And there, again like previously, "access violation error". Like FDQuery does not exist maybe ?
So my question is : When you dynamically create a Form, are all visual and non visual components of that Form automatically created ? Dbgrids appears on my Form and seems to work because data is displayed (at least in one of them), but the second FDQuery just does not want to work. I am obviously missing something here. I ruled out the FDConnection that is on the datamodule because the FDQuery1 works, so I'm out of ideas...
Thanks in advance
Math