Partager via


Managing Multiple Instances of a Form

You can have multiple instances of a class definition active at a time. For example, you can design one order form but have several open orders in your application. Each uses the same form definition but is displayed and manipulated individually.

When you have multiple instances of a form, the key points to remember are:

  • Create an array property in the launching form to hold the object variables associated with each instance of the multiple instance form. The easiest way to keep track of instance variables when you don't know ahead of time how many there will be is to use an array.
  • For the form that is to have multiple instances, set the DataSession property to 2 – Private Data Session. A private data session provides a separate set of work areas for each instance of the form so that selected tables and record pointer positions are all independent.

The following example provides code that demonstrates creating multiple instances of a form. For the sake of brevity, this code is not optimized; it is intended only to present the concepts.

The following form launches multiple instances:

Property Setting for Launch.scx

Object Property Setting
frmLaunch aForms[1]
" "

Event Code for Launch.scx

Object Event Code
cmdQuit Click
RELEASE THISFORM
cmdLaunch Click
nInstance = ALEN(THISFORM.aForms)
DO FORM Multi ;
  NAME THISFORM.aForms[nInstance] ;
  LINKED
DIMENSION ;
  THISFORM.aForms[nInstance + 1]

In refining the code in this example, you could manage the array of form objects so that empty array elements reused as forms are closed and new forms are opened, rather than always redimensioning the array and increasing the number of elements by one.

The form that can have multiple instances is Multi.scx. The data environment for this form contains the Employee table.

Multiple instances of Multi.scx

Property Setting for Multi.scx

Object Property Setting
txtFirstname ControlSource
Employee.first_name
txtLastName ControlSource
Employee.last_name
frmMulti DataSession 2 - Private Data Session

When you choose Launch Form in the Launcher form, an instance of the Multi form is created. When you close the Launcher form, the property array aForms is released and all instances of Multi are destroyed.

Visual FoxPro provides some functions and properties to help you manage multiple instances of objects. For more information, see AINSTANCE( ), AUSED( ), and DataSessionID.

See Also

Saving a Form as HTML | Setting the Design Area for a Form | Creating Forms | Creating Forms with Local and Remote Data | DataSession