0
votes

Using delphi XE7. I just want to load the frame into panel and then click button to query the label's caption property inside the frame during the runtime. I can't seem to get it working. Kindly please advise. Thanks.

Panel2 in Unit1

unit Unit1;
interface

uses
Winapi.Windows, Winapi.Messages, System.SysUtils,
System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls;

type
TForm1 = class(TForm)
 Button4: TButton;
 Panel2: TPanel;
 procedure Button4Click(Sender: TObject);
 procedure FormCreate(Sender: TObject);

private
    { Private declarations }
public
    { Public declarations }
end;

var
  Form1: TForm1;
implementation
{$R *.dfm}

uses Unit3{TFrame3};

 procedure TForm1.Button4Click(Sender: TObject);
 begin
   ShowMessage(Frame3.Label4.caption);
 end;

 procedure TForm1.FormCreate(Sender: TObject);
 begin
    Frame3.parent:=Panel2;
 end;
end.

Frame3 in this unit

unit Unit3;
interface

uses
 Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
 System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
 Vcl.StdCtrls;

type
 TFrame3 = class(TFrame)
 Label4: TLabel;
 private
 public
    constructor Create(TheOwner: TComponent); override;
    destructor Destroy; override;
 end;

var
  Frame3: TFrame3;

implementation

{$R *.dfm}

constructor TFrame3.Create(TheOwner: TComponent);
 begin
   inherited Create(TheOwner);
 end;

destructor TFrame3.Destroy;
 begin
   inherited Destroy;
 end;
end.

When compiling ok, but running into error - "First chance exception at $005E098C. Exception class $C0000005 with message 'access violation at 0x005e098c: read of address 0x00000000'. Process Project1.exe (8416)"

1
You need to instantiate Frame3 before you reference it in TForm1.FormCreate. If you placed a breakpoint on that line you would see that Frame3 = nil, hence your Access ViolationJason
Thanks. I just updated here. I add "Frame3.parent::=Panel2". How do I initiate it?user1739825
Like any other class. Frame3 := TFrame3.Create(Self); Unless Frame3 is going to be used by something other than Form1, you should remove the global Frame3 variable from Unit3 and declare it as a private field in TForm1Jason

1 Answers

2
votes

You need to first create an instance of your frame before it can be referenced in Form 1.

Set your TForm1.FormCreate event to be:

 procedure TForm1.FormCreate(Sender: TObject);
 begin
    Frame3 := TFrame3.Create(Self);
    Frame3.Align := alClient;
    Frame3.Parent := Panel2;
 end;