Search code examples
delphidbgrid

delphi using dbgrid to view a record on a detail page


I have a form with a dbgrid and a second form with dbedits. My form with the dbgrid has a double click event(code below is the event) the dbedits on the second form has a data source that is connected to the first form's CDS and when I compile and run the program and open the form with db grid I can double click any record and it is display in the dbedits on the second form, but if I close the forms and reopen the form the only record that will display in the second form dbedits is the first record in the table. I have to open and close CDS and that is not working. what else would I need to do to correct this problem.

procedure TFRM_ADMIN.DBGrid1DblClick(Sender: TObject);
BEGIN
  frm_LEADDETAILADMINLEAD := tfrm_LEADDETAILADMINLEAD.Create(FRM_ADMIN);
  frm_LEADDETAILADMINLEAD.SHOW;   
END;

The site will not allow me to add the dmf text. It is to large. I am using sqlconnection, sqlquery, data set provider, client data set, data source set up if this helps any.


Solution

  • This is a very wild quess, but I suspect the following at play:

    • You use the public variables for the forms that the IDE automatically has added to each unit.
    • You create FRM_ADMIN the way you create frm_LEADDETAILADMINLEAD, something like:

      FRM_ADMIN := TFRM_ADMIN.Create(MainForm);
      FRM_ADMIN.Show;
      
    • You don't close this form, but hide it (the default close action of a form).

    • The second time you create your second form, the designtime set DataSet property of the DataSource of your second form is automatically resolved to the ClientDataSet on the first instance of the first form.
    • So in the second run you are editing the record that was selected in the first run.

    Solution and recommendations:

    • Destroy forms (set Action := caFree) in the OnClose event.
    • Do not use the public variables, remove them. Keep you form reference in a separate private field, unique to each instance.
    • Assign DataSource and/or DataSet properties at runtime explicitly.
    • Use DataModules.

    Further reading: