Registriert seit: 7. Jun 2006
Ort: Karlsruhe
3.724 Beiträge
FreePascal / Lazarus
|
AW: Access variable from one form to another
21. Aug 2013, 00:57
If you want to access a property of Form1 (Unit1) from within Form2 (Unit2), you have to add Unit1 to the uses clause in Unit2.
Delphi-Quellcode:
unit Unit1;
interface
uses
Windows, Classes, SysUtils, Forms, Controls, Graphics, StdCtrls;
type
TForm1 = class(TForm)
{...}
end;
var
Form1: TForm1;
implementation
uses Unit2; // <--
procedure TForm1.FormClick(Sender: TObject);
begin
ShowMessage(IntToStr(Form2.OldId));
end;
Delphi-Quellcode:
unit Unit2;
interface
uses
Windows, Classes, SysUtils, Forms, Controls, Graphics, StdCtrls;
type
TForm2 = class(TForm)
{...}
private
FOldId: integer;
public
property OldId: integer read FOldId write FOldId
end;
var
Form2: TForm2;
implementation
{...}
I generally wouldn't recommend doing this though because it leads to spaghetti code.
Instead I would outsource the data and business logic to a separate class and then create all forms that operate on a specific object on demand:
Delphi-Quellcode:
unit MyData;
type
TMyData = class
private
FOldId: integer;
public
OldId: integer read FOldId write FOldId;
end;
{...}
Delphi-Quellcode:
unit Main;
uses
Windows, Classes, SysUtils, Forms, Controls, Graphics, StdCtrls,
MyData;
type
TFrmMain = class(TForm)
{ ... }
FMyData: TMyData;
end;
var
frmMain: TFrmMain;
implementation
procedure TForm1.FormClick(Sender: TObject);
var
DialogForm: TFrmDialog;
begin
DialogForm := TFrmDialog.Create(FMyData);
DialogForm.Show; // Or perhaps DialogForm.ShowModal
end;
Delphi-Quellcode:
unit FrmDialog;
uses
Windows, Classes, SysUtils, Forms, Controls, Graphics, StdCtrls,
MyData;
type
TFrmDialog = class(TForm)
{ ... }
FMyData: TMyData;
constructor Create(MyData: TMyData);
end;
// You should dispose of this global variable. You'll also have to edit the
// project's source file for this
//var
// FrmDialog: TFrmDialog ;
implementation
constructor TFrmDialog.Create(MyData: TMyData);
begin
inherited Create;
FMyData := MyData;
end;
procedure TFrmDialog.FormClick(Sender: TObject);
begin
FMyData.OldId := 1; // change the data object
end;
|
|
Zitat
|