Search code examples
delphivariablesmdiscoping

How to have a different value in a variable per each different instance of a form?


i got a mdi form which display contact address. Since it is Mdi, i could open multiple copies of the form. However, apparently the variables used gets "copied" accross the forms. Therefore in the code below, the ContactTypeId will have the value based on the the last form created.

implementation

uses DataModule, MainForm;

{$R *.dfm}

var ModuleUserLevel, ContactId, ContactTypeId : Integer;
  EditMode, EditAccess, AddAccess, DeleteAccess  : Boolean;
  ContactName : String;

constructor TContactDetailsFrm.Create(AOwner:TComponent; InContactTypeId, InContactId : Integer);
Begin
  Inherited Create(AOwner);
  ContactId := InContactId;
  ContactTypeId := InContactTypeID;
End;

How can i avoid this?

thanks in advance


Solution

  • You are using external (often referred to, a bit imprecise, as global) variables but probably want instance fields in the form class TContactDetailsFrm:

    type
      TContactDetailsFrm = class(TForm)
      private
        FModuleUserLevel, FContactId, FContactTypeId: Integer;
        FEditMode, FEditAccess, FAddAccess, FDeleteAccess: Boolean;
        FContactName: string;
      public
        { Public-Deklarationen }
      end;
    

    The F is the idiomatic prefix for private fields in Delphi.