有这样一个问题:
1.有三个窗体frmMain,frm1,frm2.
2.frmMain中有两个Panel(Panel1,Panel2)
3.当frmMain创建时,frm1和frm2也创建并分别显示在Panel1和Panel2中
4.我点击frm1中的按钮btn1,在frm2中的文本框txt1中显示'hello world!'
我是这么写的:
((Parent.Parent.Parent as TfrmMain).Panel2.Controls[0] as Tfrm2).txt1.text:='hello world';
为什么总是出现内存溢出?跟踪的时候发现第一个parent为空。

解决方案 »

  1.   

    ((Parent.Parent as TfrmMain).Panel2.Controls[0] as Tfrm2).txt1.text:='hello world';
    即可
      

  2.   

    测试代码如下:
    program Project1;uses
      Forms,
      Unit1 in 'Unit1.pas' {frmMain},
      Unit2 in 'Unit2.pas' {frm1},
      Unit3 in 'Unit3.pas' {frm2};{$R *.res}begin
      Application.Initialize;
      Application.CreateForm(TfrmMain, frmMain);
      Application.Run;
    end.
    ----------
    unit Unit1;interfaceuses
      Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
      Dialogs, ExtCtrls, StdCtrls;type
      TfrmMain = class(TForm)
        Panel1: TPanel;
        Panel2: TPanel;
        procedure FormCreate(Sender: TObject);
      private
        { Private declarations }
      public
        { Public declarations }
      end;var
      frmMain: TfrmMain;implementationuses Unit2, Unit3;{$R *.dfm}procedure TfrmMain.FormCreate(Sender: TObject);
    var
      frm1: Tfrm1;
      frm2: Tfrm2;
    begin
      frm1 := Tfrm1.Create(Self.Panel1);
      frm2 := Tfrm2.Create(Self.Panel2);
      frm1.Parent := Self.Panel1;
      frm1.Left := 0;
      frm1.Top := 1;
      frm1.Show;
      frm2.Parent := Self.Panel2;
      frm2.Left := 0;
      frm2.Top := 1;
      frm2.Show;
    end;end.
    -----------------
    unit Unit2;interfaceuses
      Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
      Dialogs, StdCtrls;type
      Tfrm1 = class(TForm)
        Label1: TLabel;
        Button1: TButton;
        procedure Button1Click(Sender: TObject);
      private
        { Private declarations }
      public
        { Public declarations }
      end;implementationuses Unit1, Unit3;{$R *.dfm}procedure Tfrm1.Button1Click(Sender: TObject);
    begin
      ((Parent.Parent as TfrmMain).Panel2.Controls[0] as Tfrm2).Label1.Caption := '22';
    end;end.
    -----------------
    unit Unit3;interfaceuses
      Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
      Dialogs, StdCtrls;type
      Tfrm2 = class(TForm)
        Label1: TLabel;
      private
        { Private declarations }
      public
        { Public declarations }
      end;implementation{$R *.dfm}end.