问题描述:

I have a form that I open multiple instances of. In there I use a SQL query to read some data from a database (Absolute Database in this case). I then fill out a few variables with data and also use the query for other operations during the lifetime of the form.

The problem is that when I open more than one instance of the form, the data change on the old forms to values from the last opened form.

I create the query in the form when it's opened so I thought that they wouldn't share the same data.

I don't use auto-created forms.

How can avoid this from happening?

** Edit - Added some code **

I create the form as follows:

procedure TfrmMain.OpenFormsFunction(Sender: TObject);

var

Resultater: TfrmregResultat;

begin

// Some code for checking if forms are already open

// Locate record in table to be used as paramdata in the query in the newly opened form

DataX.tStevneHead.Locate('StevneNummer;GrenType', VarArrayOf([StevneNummer, GrenType), []);

Resultater := TfrmRegResultat.Create(nil);

Resultater.Show; // OnClose action for the form is caFree

end;

Snip from the form's code

// decleared in implementation

Dato: TDate;

GrenType: string;

GrenRunder: integer;

MaxPoeng: integer;

procedure TfrmRegResultat.FormShow(Sender: TObject);

begin

//-- qStevneHead is a TABSQuery component on the form

//-- DataX is the name of my DataModule

with qStevneHead do

begin

Close;

SQL.Clear;

SQL.Text := 'SELECT * FROM StevneHead WHERE GrenType = :aGrenType AND StevneNummer = aStevneNummer';

ParamByName('aGrenType').AsString := DataX.tStevneHead.FieldByName('GrenType').Value;

ParamByName('aStevneNummer').AsString := DataX.tStevneHead.FieldByName('StevneNummer').Value;

Open;

end;

GrenRunder := qStevneHead.FieldByName('AntallRunder').Value;

Dato := qStevneHead.FieldByName('Dato').AsDateTime;

GrenType := qStevneHead.FieldByName('GrenType').Value;

MaxPoeng := qStevneHead.FieldByName('MaxPoeng').Value;

// More code to init stringgrid and other stuff on the form

end;

网友答案:

The problem seems to be that you're using global variables. Change them to be fields of the form and your problem should be solved. IOW, now you have

implementation

var
  Dato:        TDate;
  GrenType:    string;
  GrenRunder:  integer;
  MaxPoeng:    integer;

Change it to

type
  TfrmRegResultat = class(...)
  ...
  private
    Dato:        TDate;
    GrenType:    string;
    GrenRunder:  integer;
    MaxPoeng:    integer;
   ...
  end;

If you need to access the values from some other part of the program (ie in the main form) then make them public propertyes or fields and access them via the currently active form variable.

相关阅读:
Top