Owen
Owen

Reputation: 15

Delphi update a parent form control from a child form

From a form, I create and show a second form. From the second form I want to update a control on the first form. But I get access violations. I can get it to work with the form in the autocreate, but not when I create the form with the create method I get violations.

Below is an example. If I run it as it is with form 11 in autocreate it works (I update a button caption in the first form). But, if in unit 10, if I comment out form11.show;, and I uncomment the create and the show and then take Form11 out of autocreate, I get an access violation.

Question - How can I update the parent form from the showed form when I create the form with a create method.

Unit10

unit Unit10;
interface
uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;
type
  TForm10 = class(TForm)
     Button1: TButton;
     procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
  Form10: TForm10;
implementation
uses Unit11;
{$R *.dfm}
procedure TForm10.Button1Click(Sender: TObject);
var
  fForm     : TForm11;
Begin
//        fForm := Form11.Create(Self);  //This and next line give me access violation
//        fForm.Show;           //   with form11 out of autocreate
   form11.show;            //This works with form11 in the autocreate.
end;
end.

Unit11

unit Unit11;
interface
uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;
type
  TForm11 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;
var
  Form11: TForm11;
implementation
uses unit10;
{$R *.dfm}
procedure TForm11.Button1Click(Sender: TObject);
begin
form10.button1.caption := 'Changed';
end;
end.

Upvotes: 0

Views: 2564

Answers (2)

Emma Leis
Emma Leis

Reputation: 2900

I've always just had my forms auto-creating and can't think of a reason to not do so, but here's the likely cause of your problem:
The Create method needs to be called on a class, not on a variable.

This line would probably work to create a new instance of TForm11:


    fForm := TForm11.Create(Self);

Upvotes: 2

dan-gph
dan-gph

Reputation: 16899

This is incorrect:

fForm := Form11.Create(Self)

It should be like this:

fForm := TForm11.Create(Self)

That is, TForm11, not Form11. To create an object, you have to call the constructor via the class.

Upvotes: 8

Related Questions