user3715962
user3715962

Reputation: 25

How to Pass an Object into a Second New Delphi Form

I have an object that is created on Form1 and I would like to be able to access one of its fields on Form2. I have tried to google it and nobody can give an answer that I can understand. Please excuse me but I am a novice.

Form1

unit Unit1;
interface
uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;
type
  Ttest=class
    public
    sName:string;
  end;
type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
end;
var
  Form1: TForm1;
implementation

uses Unit2;
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
var
  myObj:Ttest;
begin
  myObj.Create;
  myObj.sName := 'Name';
  Form2.Show;
end;

end.

Form2

unit Unit2;
  interface
    uses
    Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
       Dialogs, StdCtrls;
type
   TForm2 = class(TForm)
    Button2: TButton;
    procedure Button2Click(Sender: TObject);
end;

var
 Form2: TForm2;
implementation
uses Unit1;
{$R *.dfm}

procedure TForm2.Button2Click(Sender: TObject);
begin
 ShowMessage(myObj.sName);//This is not working
end;

end.

Upvotes: 0

Views: 2003

Answers (1)

David Schwartz
David Schwartz

Reputation: 1838

You have two forms that both use an object. You should define the object in a separate unit and list it in the Uses clause in the Interface section of both forms. Try using something already defined in a main library, like TStringlist, so you don't get confused with this part.

From what you're showing here, you're attempting to create an instance of that object in one form and do something with it in another form. That's a common thing to do: you may have one unit that asks for a filename and loads a file into a TStringList, then hands that over to another form or unit to deal with.

The way you're doing it, however, can be improved to reduce coupling between the two forms.

What you want to do is define a property like this in TForm2:

TForm2 = class( TForm )
. . .
private
  Ftestobj : TTest; // or TStringlist

public
  property testobj : TTest read Ftestobj write Ftestobj;

Then in TForm1.OnButtonClick do something like this:

form2.testobj := myobj;
form2.Show;

And then this becomes:

procedure TForm2.Button2Click(Sender: TObject);
begin
 ShowMessage(Ftestobj.sName);
end;

I did a whole session in CodeRage 9 on this topic recently, in fact. It's entitled, "Have you embraced your inner plumber yet?" and it's all about moving data in and out of forms like this. (I call it plumbing code.)

Search for "coderage 9" and watch the video. At the end is a link where you can download my example code. That should keep you busy for a while. :)

Upvotes: 5

Related Questions