FoxPro - Notes
FoxPro - Notes
FoxPro - Notes
Type Examples
Numeric 123
3.1415
–7
Logical .T.
.F.
Date {^1998-01-01}
DateTime {^1998-01-01 12:30:00 p}
Manipulating Data
Containers and data types give you the building blocks you need to manipulate data. The final pieces are operators, functions, and
commands.
Using Operators
Operators tie data together. Here are the most common operators in Visual FoxPro.
Operator Valid Data Types Example Result
*, / Numeric ? 5 * 5 Prints 25
? 25 / 5 Prints 5
Note A question mark (?) in front of an expression causes a new line character and the results of the expression to be printed in the
active output window, which is usually the main Visual FoxPro window.
Remember that you must use the same type of data with any one operator. The following statements store two numeric pieces of data
to two variables. The variables have been given names that start with n so we can tell at a glance that they contain numeric data, but
you could name them with any combination of alphanumeric characters and underscores.
nFirst = 123
nSecond = 45
The following statements store two pieces of character data to two variables. The variables have been given names that start with c to
indicate that they contain character data.
cFirst = "123"
cSecond = "45"
The following two operations, addition and concatenation, yield different results because the type of data in the variables is different.
? nFirst + nSecond
? cFirst + cSecond
Output
168
12345
Because cFirst is character data and nSecond is numeric data, you get a data type mismatch error if you try the following
command:
? cFirst + nSecond
You can avoid this problem by using conversion functions. For example, STR( ) returns the character equivalent of a numeric value
and VAL( ) returns the numeric equivalent of a character string of numbers. These functions and LTRIM( ), which removes leading
spaces, enable you to perform the following operations:
? cFirst + LTRIM(STR(nSecond))
? VAL(cFirst) + nSecond
Output
12345
168
Using Functions
Page 1 of 25
Functions return a specific type of data. For example, the functions STR( ) and VAL( ), used in the previous section, return character
and numeric values, respectively. As with all functions, these return types are documented along with the functions.
There are five ways to call a Visual FoxPro function:
• Assign the return value of the function to a variable. The following line of code stores the current system date to a variable
named dToday:
• dToday = DATE( )
• Include the function call in a Visual FoxPro command. The following command sets the default directory to the value
returned from the GETDIR( ) function:
• CD GETDIR( )
• Print the return value in the active output window. The following line of code prints the current system time in the active
output window:
• ? TIME( )
• Call the function without storing the return value anywhere. The following function call turns the cursor off:
• SYS(2002)
• Embed the function in another function. The following line of code prints the day of the week:
• ? DOW(DATE( ))
Some other examples of functions used in this chapter are:
Function Description
ISDIGIT( ) Returns true (.T.) if the leftmost character in a string is a number; otherwise, returns false (.F.).
SUBSTR( ) Returns the specified number of characters from a character string, starting at a specified location in
the string.
Using Commands
A command causes a certain action to be performed. Each command has a specific syntax which indicates what must be included in
order for the command to work. There are also optional clauses associated with commands that allow you to specify in more detail
what you want.
For example, the USE command allows you to open and close tables:
USE Syntax Description
USE customer Opens the CUSTOMER table in the current work area, closing any table that was already open in the
work area.
USE customer IN 0 Opens the CUSTOMER table in the next available work area.
USE customer IN 0 ; Opens the CUSTOMER table in the next available work area and assigns the work area an alias of
ALIAS mycust mycust.
REPLACE Replaces the value stored in record field with a new value.
SCAN The code between SCAN and ENDSCAN is executed as many times
as there are records in the table. Each time the code is executed, the
record pointer moves to the next record in the table.
IF salary >= 30000.00 For each record, if the salary is greater than or equal to 30,000,
REPLACE salary WITH ; replace this value with a new salary that is 3% higher.
salary * 1.03 The semicolon (;) after WITH indicates that the command is
continued on the next line.
ELSE For each record, if the salary is not greater than or equal to 30,000,
REPLACE salary WITH ; replace this value with a new salary that is 6% higher.
salary * 1.06
This example uses both conditional branching and looping commands to control the flow of the program.
Conditional Branching
Conditional branching allows you to test conditions and then, depending on the results of that test, perform different operations. There
are two commands in Visual FoxPro that allow conditional branching:
• IF ... ELSE ... ENDIF
• DO CASE ... ENDCASE
The code between the initial statement and the ENDIF or ENDCASE statement is executed only if a logical condition evaluates to
true (.T.). In the example program, the IF command is used to distinguish between two states: either the salary is $30,000 or more, or
it isn’t. Different actions are taken depending on the state.
In the following example, if the value stored in the variable nWaterTemp is less than 100, no action is taken:
* set a logical variable to true if a condition is met.
IF nWaterTemp >= 100
lBoiling = .T.
ENDIF
Note An asterisk at the beginning of a line in a program indicates that the line is a comment. Comments help the programmer
remember what each segment of code is designed to do, but are ignored by Visual FoxPro.
If there are several possible conditions to check for, a DO CASE ... ENDCASE block can be more efficient and easier to keep track of
than multiple IF statements.
Looping
Looping allows you to execute one or more lines of code as many times as you need to. There are three commands in Visual FoxPro
that allow looping:
• SCAN ... ENDSCAN
• FOR ... ENDFOR
• DO WHILE ... ENDDO
Use SCAN when you are performing a series of actions for each record in a table, as in the example program just described. The
SCAN loop enables you to write the code once and have it executed for each record as the record pointer moves through the table.
Use FOR when you know how many times the section of code needs to be executed. For example, you know there are a specific
number of fields in a table. Because the Visual FoxPro function FCOUNT( ) returns this number, you can use a FOR loop to print the
names of all the fields in the table:
FOR nCnt = 1 TO FCOUNT( )
? FIELD(nCnt)
ENDFOR
Use DO WHILE when you want to execute a section of code as long as a certain condition is met. You might not know how many
times the code will have to execute, but you know when it should stop executing. For example, let’s assume you have a table with
people’s names and initials, and you want to use the initials to look people up. You would have a problem the first time you tried to
add a person who had the same initials as someone else already in your table.
To solve the problem, you could add a number to the initials. For example, Michael Suyama’s identification code could be MS. The
next person with the same initials, Margaret Sun, would be MS1. If you then added Michelle Smith to the table, her identification
code would be MS2. A DO WHILE loop enables you to find the right number to append to the initials.
Page 3 of 25
Sample Program with DO WHILE to Generate a Unique ID
Code Comments
cInitials = LEFT(firstname,1) + ; Get the person’s initials from the first letters of the firstname and
LEFT(lastname,1) lastname fields.
nSuffix = 0 Establish a variable to hold the number to be added to the end of a
person’s initials if necessary.
LOCATE FOR person_id = cInitials See if there is another person in the table with the same initials.
DO WHILE FOUND( ) If another record in the table has a person_id value that is the same as
cInitials, the FOUND( ) function returns true (.T.) and the code
in the DO WHILE loop executes.
If no match is found, the next line of code to be executed is the line
following ENDDO.
nSuffix = nSuffix + 1 Prepare a fresh suffix and append it to the end of the initials.
cInitials = ;
LEFT(cInitials,2);
+ ALLTRIM(STR(nSuffix))
GOTO nHere Return to the record and store the unique identification code in the
REPLACE person_id WITH cInitials person_id field.
Because you can’t know beforehand how many times you’ll find matching identification codes already in use, you use the DO
WHILE loop.
To create a new program
1. Type the following command in the Command window:
2. MODIFY COMMAND numonly
3. In the window that opens, type the following lines of code:
4. FOR nCnt = 1 TO 14
5. ? SUBSTR(cTest, nCnt, 1)
6. ENDFOR
Now that you’ve created a program, you can run it.
To run a program
1. In the open program window, press CTRL+E.
2. If a Save dialog box appears, choose OK.
When you run this program, the individual characters in the test string are printed on separate lines in the main Visual FoxPro
window.
DO myproc WITH cTestString Calls a procedure and passes a literal string or character
DO myproc WITH "test string" variable.
Note If you call a procedure or function without using the DO command, the UDFPARMS setting controls how parameters are
passed. By default, UDFPARMS is set to VALUE, so copies of the parameters are passed. When you use DO, the actual parameter is
used (the parameter is passed by reference), and any changes within the procedure or function are reflected in the original data,
regardless of the setting of UDFPARMS.
You can send multiple values to a procedure or function by separating them with commas. For example, the following procedure
expects three parameters: a date, a character string, and a number.
PROCEDURE myproc( dDate, cString, nTimesToPrint )
FOR nCnt = 1 to nTimesToPrint
? DTOC(dDate) + " " + cString + " " + STR(nCnt)
ENDFOR
ENDPROC
You could call this procedure with this line of code:
DO myproc WITH DATE(), "Hello World", 10
Receiving Values from a Function
The default return value is true (.T.), but you can use the RETURN command to return any value. For example, the following
function returns a date that is two weeks later than date passed to it as a parameter.
FUNCTION plus2weeks
PARAMETERS dDate
RETURN dDate + 14
ENDFUNC
The following line of code stores the value returned from this function to a variable:
dDeadLine = plus2weeks(DATE())
The following table lists the ways you can store or display values returned from a function:
Manipulating Return Values
Code Comments
? myfunc( ) Prints the value returned by the function in the active output window.
Page 5 of 25
Verifying Parameters in a Procedure or Function
It’s a good idea to verify that the parameters sent to your procedure or function are what you expect to receive. You can use the
TYPE( ) and PARAMETERS( ) functions to verify the type and number of parameters sent to your procedure or function.
The example in the previous section, for instance, needs to receive a Date type parameter. You can use the TYPE( ) function to make
sure the value your function receives is the right type.
FUNCTION plus2weeks( dDate )
IF TYPE("dDate") = "D"
RETURN dDate + 14
ELSE
MESSAGEBOX( "You must pass a date!" )
RETURN { - - } && Return an empty date
ENDIF
ENDFUNC
If a procedure expects fewer parameters than it receives, Visual FoxPro generates an error message. For example, if you listed two
parameters, but you call the procedure with three parameters, you’ll get an error message. But if a procedure expects more parameters
than it receives, the additional parameters are simply initialized to false (.F.). Because there is no way to tell whether the last
parameter was set to false (.F.) or omitted, the following procedure checks to make sure the appropriate number of parameters was
sent:
PROCEDURE SaveValue( cStoreTo, cNewVal, lIsInTable )
IF PARAMETERS( ) < 3
MESSAGEBOX( "Too few parameters passed." )
RETURN .F.
ENDIF
IF lIsInTable
REPLACE (cStoreTo) WITH (cNewVal)
ELSE
&cStoreTo = cNewVal
ENDIF
RETURN .T.
ENDPROC
Converting the NUMONLY Program to a Function
NUMONLY.PRG, the example program discussed earlier in The Process of Programming section, can be made more robust and
useful by creating a function for the part of the program that removes the non-numeric characters from a string.
Sample Procedure to Return Numeric Characters from a String
Code Comments
FUNCTION NumbersOnly( cMixedVal ) Start of the function, which accepts a character string.
cNumOnly = "" Create a string that has only the numeric characters from the original
FOR nCnt = 1 TO LEN(cMixedVal) string.
cCharacter = ;
SUBSTR(cMixedVal, nCnt, 1)
IF ISDIGIT(cCharacter)
cNumOnly = ;
cNumOnly + cCharacter
ENDIF
ENDFOR
RETURN cNumOnly Return the string that has only numeric characters.
In addition to allowing you to use this code in multiple situations, this function makes the program easier to read:
SCAN
REPLACE FieldName WITH NumbersOnly(FieldName)
ENDSCAN
Or, even more simply:
REPLACE ALL FieldName WITH NumbersOnly(FieldName)
Page 6 of 25
Chapter 3: Object-Oriented Programming
While Visual FoxPro still supports standard procedural programming, new extensions to the language give you the power and
flexibility of object-oriented programming.
Object-oriented design and object-oriented programming represent a change in focus from standard procedural programming. Instead
of thinking about program flow from the first line of code to the last line of code, you need to think about creating objects: self-
contained components of an application that have private functionality as well as functionality that you can expose to the user.
This chapter discusses:
• Understanding Objects in Visual FoxPro
• Understanding Classes in Visual FoxPro
• Matching the Class to the Task
• Creating Classes
• Adding Classes to Forms
• Defining Classes Programmatically
Understanding Objects in Visual FoxPro
In Visual FoxPro, forms and controls are objects that you include in your applications. You manipulate these objects through their
properties, events, and methods.
The object-oriented Visual FoxPro language extensions provide you with a great deal of control over the objects in your applications.
These extensions also make it easier to create and maintain libraries of reusable code, giving you:
• More compact code.
• Easier incorporation of code into applications without elaborate naming schemes.
• Less complexity when integrating code from different files into an application.
Object-oriented programming is largely a way of packaging code so that it can be reused and maintained more easily. The primary
package is called a class.
Classes and Objects:
The Building Blocks of Applications
Classes and objects are closely related, but they are not the same. A class contains information about how an object should look and
behave. A class is the blueprint or schematic of an object. The electrical schematic and design layout of a telephone, for example,
would approximate a class. The object, or an instance of the class, would be a telephone.
The class determines the characteristics of the object.
MousePointer How the mouse pointer looks when over the check box.
The following table lists some of the methods associated with a check box:
Method Description
Refresh The value of the check box is updated to reflect any changes that may have occurred to the
underlying data source.
SetFocus The focus is set to the check box just as though the user had pressed the TAB key until the check box
was selected.
See Chapter 4, Understanding the Event Model, for a discussion of the order in which events occur.
Understanding Classes in Visual FoxPro
All of the properties, events, and methods for an object are specified in the class definition. In addition, classes have the following
characteristics that make them especially useful for creating reusable, easily maintained code:
• Encapsulation
• Subclasses
• Inheritance
Hiding Unnecessary Complexity
When you include a phone in your office, you probably don’t care how the phone internally receives a call, initiates or terminates
connections to electronic switchboards, or translates key presses into electronic signals. All you need to know is that you can lift the
receiver, dial the appropriate numbers, and talk to the person you want to talk to. The complexity of making that connection is hidden.
The benefit of being able to ignore the inner details of an object so you can focus on the aspects of the object you need to use is called
abstraction.
Internal complexity can be hidden.
Encapsulation, which involves packaging method and property code together in an object, contributes to abstraction. For example, the
properties that determine the items in a list box and the code that executes when you choose an item in the list can be encapsulated in
a single control that you add to a form.
Leveraging the Power of Existing Classes
A subclass can have all the functionality of an existing class, plus any additional controls or functionality you want to give it. If your
class is a basic telephone, you can have subclasses that have all the functionality of the original telephone and any specialized features
you want to give them.
Subclassing allows you to reuse code.
Subclassing is one way to decrease the amount of code you have to write. Start with the definition of an object that is close to what
you want, and customize it.
Streamlining Code Maintenance
With inheritance, if you make a change to a class, that change is reflected in all subclasses based on the class. This automatic update
saves you time and effort. For example, if a phone manufacturer wanted to change from dial to push-button style phones, it would
save a lot of work to be able to make the change to the master schematic and have all previously manufactured phones based on that
master schematic automatically inherit this new feature, rather than having to add the new feature to all the existing phones
individually.
Inheritance makes maintaining your code easy.
Inheritance doesn’t work with hardware, but you do have this capability in software. If you discover a bug in your class, instead of
having to go to each subclass and change the code, you fix it once in the class and the change propagates throughout all subclasses of
the class.
The Visual FoxPro Class Hierarchy
When you are creating user-defined classes, it helps to understand the Visual FoxPro class hierarchy.
The Visual FoxPro class hierarchy
Page 8 of 25
Containers and Non-Containers
The two primary types of Visual FoxPro classes, and by extension Visual FoxPro objects, are container classes and control classes.
Container and Control Classes
Container Classes
Containers can contain other objects and allow access to the objects contained within them. For example, if you create a container
class that consists of two list boxes and two command buttons, and then add an object based on this class to a form, each individual
object can be manipulated at run time and design time. You can easily change the positions of the list boxes or the captions of the
command buttons. You can also add objects to the control at design time; for example, you can add labels to identify the list boxes.
The following table lists what each container class can contain:
Container Can contain
Grid columns Headers and any objects except form sets, forms, toolbars, timers, and other
columns
Control Classes
Control classes are more completely encapsulated than container classes are, but can be less flexible for that reason. Control classes
do not have an AddObject method.
Matching the Class to the Task
You want to be able to use classes in many different contexts. Smart planning will enable you to most effectively decide what classes
to design and what functionality to include in the class.
Deciding When to Create Classes
You could create a class for every control and every form you might ever use, but this isn’t the most effective way to design your
applications. You’ll likely end up with multiple classes that do much the same thing but must be maintained separately.
Encapsulate Generic Functionality
You can create a control class for generic functionality. For example, command buttons that allow a user to move the record pointer
in a table, a button to close a form, and a help button, can all be saved as classes and added to forms any time you want the forms to
have this functionality.
You can expose properties and methods on a class so that the user can integrate them into the particular data environment of a form or
form set.
Provide a Consistent Application Look and Feel
You can create form set, form, and control classes with a distinctive appearance so that all the components of your application have
the same look. For example, you could add graphics and specific color patterns to a form class and use that as a template for all forms
you create. You could create a text box class with a distinctive appearance, such as a shadowed effect, and use this class throughout
your application any time you want to add a text box.
Deciding What Type of Class to Create
Visual FoxPro allows you to create several different kinds of classes, each with its own characteristics. You specify the type of class
you want to create in the New Class dialog box or in the AS clause in the CREATE CLASS command.
The Visual FoxPro Base Classes
You can create subclasses of most of the Visual FoxPro base classes in the Class Designer.
Page 9 of 25
Visual FoxPro Base Classes
ActiveDoc Custom Label PageFrame
* These classes are an integral part of a parent container and cannot be subclassed in the Class Designer.
All Visual FoxPro base classes recognize the following minimum set of events:
Event Description
Error Occurs whenever an error occurs in event or method procedures of the class.
All Visual FoxPro base classes have the following minimum set of properties:
Property Description
BaseClass The base class it was derived from, such as Form, Commandbutton, Custom, and so on.
ParentClass The class that the current class was derived from. If the class was derived directly from a Visual
FoxPro base class, the ParentClass property is the same as the BaseClass property.
The Class Designer provides the same interface that the Form Designer does, allowing you to see and edit the properties of your class
in the Properties window. Code editing windows allow you to write code to be executed when events occur or methods are called.
Adding Objects to a Control or Container Class
If you base the new class on the control or container class, you can add controls to it the same way you add controls in the Form
Designer: choose the control button on the Form Controls toolbar and drag to size in the Class Designer.
No matter what type of class you base the new class on, you can set properties and write method code. You can also create new
properties and methods for the class.
Adding Properties and Methods to a Class
You can add as many new properties and methods to the new class as you want. Properties hold values; methods hold procedural code
to be run when you call the method.
Creating New Properties and Methods
When you create new properties and methods for classes, the properties and methods are scoped to the class, not to individual
components in the class.
To add a new property to a class
1. From the Class menu, choose New Property.
2. In the New Property dialog box, type the name of the property.
3. Specify the visibility: Public, Protected, or Hidden.
A Public property can be accessed anywhere in your application. Protected and Hidden properties and methods are discussed
in “Protecting and Hiding Class Members” later in this chapter.
New Property dialog box
Page 11 of 25
4. Choose Add.
You can also include a description of the property that will be displayed at the bottom of the Properties window in the Class
Designer and in the Form Designer when the control is added to a form.
Troubleshooting When you add a property to a class that can be set by a user of the class, the user could enter an invalid setting for
your property that could cause run-time errors. You need to explicitly document the valid settings for the property. If your property
can be set to 0, 1, or 2, for example, say so in the Description box of the New Property dialog box. You might also want to verify the
value of the property in code that references it.
To create an array property
• In the Name box of the New Property dialog box, specify the name, size, and dimensions of the array.
For example, to create an array property named myarray with ten rows and two columns, type the following in the Name
box:
myarray[10,2]
The array property is read-only at design time and is displayed in the Properties window in italics. The array property can be managed
and redimensioned at run time. For an example of using an array property, see “Managing Multiple Instances of a Form” in Chapter
9, Creating Forms.
To add a new method to a class
1. From the Class menu, choose New Method.
2. In the New Method dialog box, type the name of the method.
3. Specify the visibility: Public, Protected, or Hidden.
4. Select the Access check box to create an Access method, select the Assign check box to create an Assign method, or select
both check boxes to create Access and Assign methods.
Access and Assign methods let you execute code when the value of a property is queried or when you attempt to change the
property’s value.
The code in an Access method is executed when the value of a property is queried, typically by using the property in an object
reference, storing the value of the property to a variable, or displaying the value of property with a question mark (?).
The code in an Assign method is executed when you attempt to change the value of a property, typically by using the STORE or =
command to assign a new value to the property.
For more information about Access and Assign methods, see Access and Assign Methods.
You can also include a description of the method.
Protecting and Hiding Class Members
Properties and methods in a class definition are Public by default: code in other classes or procedures can set the properties or call the
methods. Properties and methods that you designate as Protected can be accessed only by other methods in the class definition or in
subclasses of the class. Properties and methods designated as Hidden can be accessed only by other members in the class definition.
Subclasses of the class cannot “see” or reference hidden members.
To ensure correct functioning in some classes, you need to prevent users from programmatically changing the properties or calling the
method from outside the class.
The following example illustrates using protected properties and methods in a class.
The stopwatch class included in Samples.vcx, in the Visual Studio …\Samples\Vfp98\Classes directory, includes a timer and five
labels to display the elapsed time:
The stopwatch class in Samples.vcx
lblSeconds Caption 00
lblColon1 Caption :
lblMinutes Caption 00
lblColon2 Caption :
lblHours Caption 00
This class also has three protected properties, nSec, nMin, and nHour, and one protected method, UpdateDisplay. The other three
custom methods in the class, Start, Stop, and Reset, are not protected.
Tip Choose Class Info on the Class menu to see the visibility of all properties and methods of a class.
The protected properties are used in internal calculations in the UpdateDisplay method and the Timer event. The UpdateDisplay
method sets the captions of the labels to reflect the elapsed time.
The UpdateDisplay Method
Page 12 of 25
Code Comments
THIS.lblSeconds.Caption = ; Set the label captions, retaining the leading 0 if the value
IIF(THIS.nSec < 10, ; of the numeric property is less than 10.
"0" ,"") + cSecDisplay
THIS.lblMinutes.Caption = ;
IIF(THIS.nMin < 10, ;
"0", "") + cMinDisplay
THIS.lblHours.Caption = ;
IIF(THIS.nHour < 10, ;
"0", "") + cHourDisplay
THIS.Parent.nSec = THIS.Parent.nSec + 1 Increment the nSec property every time the timer event
IF THIS.Parent.nSec = 60 fires: every second.
THIS.Parent.nSec = 0 If nSec has reached 60, reset it to 0 and increment the
THIS.Parent.nMin = ; nMin property.
THIS.Parent.nMin + 1
ENDIF
The stopwatch class has three methods that are not protected: Start, Stop, and Reset. A user can call these methods directly to control
the stopwatch.
The Start method contains the following line of code:
THIS.tmrSWatch.Enabled = .T.
The Stop method contains the following line of code:
THIS.tmrSWatch.Enabled = .F.
The Reset method sets the protected properties to zero and calls the protected method:
THIS.nSec = 0
THIS.nMin = 0
THIS.nHour = 0
THIS.UpdateDisplay
The user cannot directly set these properties or call this method, but code in the Reset method can.
Specifying the Default Value for a Property
When you create a new property, the default setting is false (.F.). To specify a different default setting for a property, use the
Properties window. In the Other tab, click on your property and set it to the desired value. This will be the initial property setting
when the class is added to a form or form set.
You can also set any of the base class properties in the Class Designer. When an object based on the class is added to the form, the
object reflects your property settings rather than the Visual FoxPro base class property settings.
Tip If you want to make the default setting of a property an empty string, select the setting in the Property Editing box and press the
BACKSPACE key.
Specifying Design Time Appearance
You can specify the toolbar icon and the container icon for your class in the Class Info dialog box.
To set a toolbar icon for a class
1. In the Class Designer, choose Class Info from the Class menu.
2. In the Class Info dialog box, type the name and path of the .BMP file in the Toolbar icon box.
Page 13 of 25
Tip The bitmap (.bmp file) for the toolbar icon is 15 by 16 pixels. If the picture is larger or smaller, it is sized to 15 by 16
pixels and might not look the way you want it to.
The toolbar icon you specify is displayed in the Form Controls toolbar when you populate the toolbar with the classes in your class
library.
You can also specify the icon to be displayed for the class in the Project Manager and Class Browser by setting the container icon.
To set a container icon for a class
1. In the Class Designer, choose Class Info from the Class menu.
2. In the Container icon box, type the name and path of the .bmp file to be displayed on the button in the Form Controls
toolbar.
Using Class Library Files
Every visually designed class is stored in a class library with a .vcx file extension.
Creating a Class Library
You can create a class library in one of three ways.
To create a class library
• When you create a class, specify a new class library file in the Store In box of the New Class dialog box.
-or-
• Use the CREATE CLASS command, specifying the name of the new class library.
For example, the following statement creates a new class named myclass and a new class library named new_lib:
CREATE CLASS myclass OF new_lib AS CUSTOM
-or-
• Use the CREATE CLASSLIB command.
For example, type the following command in the Command window to create a class library named new_lib:
CREATE CLASSLIB new_lib
Copying and Removing Class Library Classes
Once you add a class library to a project, you can easily copy classes from one library to another or simply remove classes from
libraries.
To copy a class from one library to another
1. Make sure both libraries are in a project (not necessarily the same project).
2. In the Project Manager, select the Classes tab.
3. Click the plus sign (+) to the left of the class library that the class is now in.
4. Drag the class from the original library and drop it in the new library.
Tip For convenience and speed, you might want to keep a class and all the subclasses based on it in one class library. If you
have a class that contains elements from many different class libraries, these libraries must all be open, so it will take a little
longer to initially load your class at run time and at design time.
To remove a class from a library
• Select the class in the Project Manager and choose Remove.
-or-
• Use the REMOVE CLASS command.
To change the name of a class in a class library, use the RENAME CLASS command. Remember, however, that when you change the
name of a class, forms that contain the class and subclasses in other .vcx files continue to reference the old name and will no longer
function correctly.
Visual FoxPro includes a Class Browser to facilitate using and managing classes and class libraries. For more information, see Class
Browser window.
Adding Classes to Forms
You can drag a class from the Project Manager to the Form Designer or to the Class Designer. You can also register your classes so
that they can be displayed directly on the Form Controls toolbar in the Class Designer or Form Designer and added to containers the
same way the standard controls are added.
To register a class library
1. From the Tools menu, choose Options.
2. In the Options dialog box, choose the Controls tab.
3. Select Visual Class Libraries and choose Add.
4. In the Open dialog box, choose a class library to add to the registry and choose Open.
5. Choose Set as Default if you want the class library to be available in the Form Controls toolbar in future sessions of Visual
FoxPro.
You can also add your class library to the Form Controls toolbar by choosing Add in the submenu of the View Classes button. To
make these classes available in the Form Controls toolbar in future sessions of Visual FoxPro, you still need to set the default in the
Options dialog box.
Overriding Default Property Settings
When you add objects based on a user-defined class to a form, you can change the settings of all the properties of the class that are
not protected, overriding the default settings. If you change the class properties in the Class Designer later, the settings in the object
on the form are not affected. If you have not changed a property setting in the form and you change the property setting in the class,
the change will take effect in the object as well.
Page 14 of 25
For example, a user could add an object based on your class to a form and change the BackColor property from white to red. If you
change the BackColor property of the class to green, the object on the user’s form will still have a background color of red. If, on the
other hand, the user did not change the BackColor property of the object and you changed the background color of the class to green,
the BackColor property of the object on the form would inherit the change and also be green.
Calling Parent Class Method Code
An object or class based on another class automatically inherits the functionality of the original. However, you can easily override the
inherited method code. For example, you can write new code for the Click event of a class after you subclass it or after you add an
object based on the class to a container. In both cases, the new code is executed at run time; the original code is not executed.
More frequently, however, you want to add functionality to the new class or object while keeping the original functionality. In fact,
one of the key decisions you have to make in object-oriented programming is what functionality to include at the class level, at the
subclass level, and at the object level. You can optimize your class design by using the DODEFAULT( ) function or scope resolution
operator (::) to add code at different levels in the class or container hierarchy.
Adding Functionality to Subclasses
You can call the parent class code from a subclass by using the DODEFAULT( ) function.
For example, cmdOK is a command button class stored in Buttons.vcx, located in the Visual Studio …\Samples\Vfp98\Classes
directory. The code associated with the Click event of cmdOk releases the form the button is on. CmdCancel is a subclass of cmdOk
in the same class library. To add functionality to cmdCancel to discard changes, for example, you could add the following code to
the Click event:
IF USED( ) AND CURSORGETPROP("Buffering") != 1
TABLEREVERT(.T.)
ENDIF
DODEFAULT( )
Because changes are written to a buffered table by default when the table is closed, you don’t need to add TABLEUPDATE( ) code to
cmdOk. The additional code in cmdCancel reverts changes to the table before calling the code in cmdOk, the ParentClass, to
release the form.
Class and Container Hierarchies
The class hierarchy and the container are two separate entities. Visual FoxPro looks for event code up through the class hierarchy,
whereas objects are referenced in the container hierarchy. The following section, “Referencing Objects in the Container Hierarchy,”
discusses container hierarchies. Later in this chapter, class hierarchies are explained in the section Calling Event Code up the Class
Hierarchy.
Referencing Objects in the Container Hierarchy
To manipulate an object, you need to identify it in relation to the container hierarchy. For example, to manipulate a control on a form
in a form set, you need to reference the form set, the form, and then the control.
You can compare the referencing of an object within its container hierarchy to giving Visual FoxPro an address to your object. When
you describe the location of a house to someone outside your immediate frame of reference, you need to indicate the country, the state
or region, the city, the street, or just the street number of the house, depending on how far they are from you. Otherwise, there could
be some confusion.
The following illustration shows a possible container nesting situation.
Nested containers
To disable the control in the grid column, you need to provide the following address:
Formset.Form.PageFrame.Page.;
Grid.Column.Control.Enabled = .F.
The ActiveForm property of the application object (_VFP) allows you to manipulate the active form even if you don’t know the name
of the form. For example, the following line of code changes the background color of the active form, no matter what form set it
belongs to:
_VFP.ActiveForm.BackColor = RGB(255,255,255)
Similarly, the ActiveControl property allows you to manipulate the active control on the active form. For example, the following
expression entered in the Watch window displays the name of the active control on a form as you interactively choose the various
controls:
_VFP.ActiveForm.ActiveControl.Name
Relative Referencing
When you are referencing objects from within the container hierarchy (for example, in the Click event of a command button on a
form in a form set), you can use some shortcuts to identify the object you want to manipulate. The following table lists properties or
keywords that make it easier to reference an object from within the object hierarchy:
Property or keyword Reference
Page 15 of 25
THISFORMSET The form set that contains the object.
Note You can use THIS, THISFORM, and THISFORMSET only in method or event code.
The following table provides examples of using THISFORMSET, THISFORM, THIS, and Parent to set object properties:
Command Where to include the command
THISFORMSET.frm1.cmd1.Caption = "OK" In the event or method code of any controls on any form
in the form set.
THISFORM.cmd1.Caption = "OK" In the event or method code of any control on the same
form that cmd1 is on.
Setting Properties
You can set the properties of an object at run time or design time.
To set a property
• Use this syntax:
Container.Object.Property = Value
For example, the following statements set various properties of a text box named txtDate on a form named
frmPhoneLog:
frmPhoneLog.txtDate.Value = DATE( ) && Display the current date
frmPhoneLog.txtDate.Enabled = .T. && The control is enabled
frmPhoneLog.txtDate.ForeColor = RGB(0,0,0) && black text
frmPhoneLog.txtDate.BackColor = RGB(192,192,192) && gray background
For the property settings in the preceding examples, frmPhoneLog is the highest level container object. If frmPhoneLog were
contained in a form set, you would also need to include the form set in the parent path:
frsContacts.frmPhoneLog.txtDate.Value = DATE( )
Setting Multiple Properties
The WITH ... ENDWITH structure simplifies setting multiple properties. For example, to set multiple properties of a column in a grid
in a form in a form set, you could use the following syntax:
WITH THISFORMSET.frmForm1.grdGrid1.grcColumn1
.Width = 5
.Resizable = .F.
.ForeColor = RGB(0,0,0)
.BackColor = RGB(255,255,255)
.SelectOnEntry = .T.
ENDWITH
Calling Methods
Once an object has been created, you can call the methods of that object from anywhere in your application.
To call a method
• Use this syntax:
Parent.Object.Method
The following statements call methods to display a form and set the focus to a text box:
frsFormSet.frmForm1.Show
frsFormSet.frmForm1.txtGetText1.SetFocus
Methods that return values and are used in expressions must end in open and closed parentheses. For example, the following
statement sets the caption of a form to the value returned from the user-defined method GetNewCaption:
Form1.Caption = Form1.GetNewCaption( )
Note Parameters passed to methods must be included in parentheses after the method name; for example,
Form1.Show(nStyle). passes nStyle to Form1’s Show method code.
Responding to Events
The code you include in an event procedure is executed when the event takes place. For example, the code you include in the Click
event procedure of a command button is executed when the user clicks the command button.
You can programmatically cause Click, DblClick, MouseMove, and DragDrop events with the MOUSE command, or use the
ERROR command to generate Error events and the KEYBOARD command to generate KeyPress events. You cannot
programmatically cause any other events to occur, but you can call the procedure associated with the event. For example, the
following statement causes the code in the Activate event of frmPhoneLog to be executed, but it doesn’t activate the form:
Page 16 of 25
frmPhoneLog.Activate
If you do want to activate the form, use the Show method of the form. Calling the Show method causes the form to be displayed and
activated, at which point the code in the Activate event is also executed:
frmPhoneLog.Show
Defining Classes Programmatically
You can define classes visually in the Class Designer and the Form Designer or programmatically in .PRG files. This section
describes how to write class definitions. For information about the specific commands, functions, and operators, see Help. For more
information about forms, see Chapter 9, Creating Forms.
In a program file, you can have program code prior to the class definitions, but not after the class definitions, in the same way that
program code cannot come after procedures in a program. The basic shell for class creation has this syntax:
DEFINE CLASS ClassName1 AS ParentClass [OLEPUBLIC]
[[PROTECTED | HIDDEN PropertyName1, PropertyName2 ...]
[Object.]PropertyName = eExpression ...]
[ADD OBJECT [PROTECTED] ObjectName AS ClassName2 [NOINIT]
[WITH cPropertylist]]...
[[PROTECTED | HIDDEN] FUNCTION | PROCEDURE Name[_ACCESS | _ASSIGN]
[NODEFAULT]
cStatements
[ENDFUNC | ENDPROC]]...
ENDDEFINE
Protecting and Hiding Class Members
You can protect or hide properties and methods in a class definition with the PROTECTED and HIDDEN keywords of the DEFINE
CLASS command.
For example, if you create a class to hold employee information, and you don’t want users to be able to change the hire date, you can
protect the HireDate property. If users need to find out when an employee was hired, you can include a method to return the hire date.
DEFINE CLASS employee AS CUSTOM
PROTECTED HireDate
First_Name = ""
Last_Name = ""
Address = ""
HireDate = { - - }
PROCEDURE GetHireDate
RETURN This.HireDate
ENDPROC
ENDDEFINE
Creating Objects from Classes
When you have saved a visual class, you can create an object based on it with the CREATEOBJECT( ) function. The following
example demonstrates running a form saved as a class definition in the class library file Forms.vcx:
Creating and Showing a Form Object Whose Class Was Designed in the Form Designer
Code Comments
SET CLASSLIB TO Forms ADDITIVE Set the class library to the .vcx file that the form definition was saved
in. The ADDITIVE keyword prevents this command from closing
any other class libraries that happened to be open.
frmTest = CREATEOBJECT("TestForm") This code assumes that the name of the form class saved in the class
library is TestForm.
DEFINE CLASS Navbutton AS Define the parent class of the navigation buttons.
COMMANDBUTTON
Give the class some dimensions.
Height = 25 Include a custom property, TableAlias, to hold the name of the
Width = 25 alias to navigate through.
TableAlias = ""
PROCEDURE Click If TableAlias has been set, this parent class procedure selects the
IF NOT EMPTY(This.TableAlias) alias before the actual navigation code in the subclasses is executed.
SELECT (This.TableAlias) Otherwise, assume that the user wants to navigate through the table in
ENDIF the currently selected work area.
ENDPROC
The specific navigation buttons are all based on the Navbutton class. The following code defines the Top button for the set of
navigation buttons. The remaining three navigation buttons are defined in the following table. The four class definitions are similar,
so only the first one has extensive comments.
Definition of the Top Navigation Button Class
Code Comments
DEFINE CLASS navTop AS Navbutton Define the Top navigation button class and set the Caption property.
Caption = "|<"
PROCEDURE Click Create method code to be executed when the Click event for the
control occurs.
DODEFAULT( ) Call the Click event code in the parent class, Navbutton, so that the
appropriate alias can be selected if the TableAlias property has been
set.
GO TOP Include the code to set the record pointer to the first record in the
table: GO TOP.
THIS.RefreshForm Call the RefreshForm method in the parent class. It is not necessary to
use the scope resolution operator (::) in this case because there is no
Page 19 of 25
method in the subclass with the same name as the method in the
parent class. On the other hand, both the parent and the subclass have
method code for the Click event.
DEFINE CLASS navNext AS Navbutton Define the Next navigation button class and set the Caption property.
Caption = ">"
PROCEDURE Click
DODEFAULT( )
SKIP 1
IF EOF( ) Include the code to set the record pointer to the next record in the
GO BOTTOM table.
ENDIF
THIS.RefreshForm
ENDPROC
ENDDEFINE End the class definition.
DEFINE CLASS navPrior AS Navbutton Define the Prior navigation button class and set the Caption property.
Caption = "<"
PROCEDURE Click
DODEFAULT( )
SKIP –1
IF BOF( ) Include the code to set the record pointer to the previous record in the
GO TOP table.
ENDIF
THIS.RefreshForm
ENDPROC
ENDDEFINE End the class definition.
DEFINE CLASS navBottom AS Define the Bottom navigation button class and set the Caption
Navbutton property.
Caption = ">|"
PROCEDURE Click
DODEFAULT( )
GO BOTTOM Include the code to set the record pointer to the bottom record in the
THIS.RefreshForm table.
ENDPROC
ENDDEFINE End the class definition.
The following class definition contains all four navigation buttons so that they can be added as a unit to a form. The class also
includes a method to set the TableAlias property of the buttons.
Definition of a Table Navigation Control Class
Code Comments
DEFINE CLASS vcr AS CONTAINER Begin the class definition. The Height property is set to
Height = 25 the same height as the command buttons it will contain.
Width = 100
Left = 3
Top = 3
Page 20 of 25
WITH Left = 25
ADD OBJECT cmdNext AS navNext ;
WITH Left = 50
ADD OBJECT cmdBot AS navBottom ;
WITH Left = 75
Once you have defined the class, you can subclass it or add it to a form.
Creating a Subclass Based on the New Class
You can also create subclasses based on vcr that have additional buttons such as Search, Edit, Save, and Quit. For example, vcr2
includes a Quit button:
Table navigation buttons with a button to close the form
DEFINE CLASS vcr2 AS vcr Define a class based on vcr and add a command button to it.
ADD OBJECT cmdQuit AS
COMMANDBUTTON WITH ;
Caption = "Quit",;
Height = 25, ;
Width = 50
Width = THIS.Width + THIS.cmdQuit.Width
cmdQuit.Left = THIS.Width - ;
THIS.cmdQuit.Width
PROCEDURE cmdQuit.CLICK When the user clicks cmdQuit, this code releases the form.
RELEASE THISFORM
ENDPROC
Vcr2 has everything that vcr does, plus the new command button, and you don’t have to rewrite any of the existing code.
Changes to VCR Reflected in the Subclass
Because of inheritance, changes to the parent class are reflected in all subclasses based on the parent. For example, you could let the
user know that the bottom of the table has been reached by changing the IF EOF( ) statement in navNext.Click to the
following:
IF EOF( )
GO BOTTOM
SET MESSAGE TO "Bottom of the table"
ELSE
SET MESSAGE TO
ENDIF
You could let the user know that the top of the table has been reached by changing the IF BOF( ) statement in
navPrior.Click to the following:
Page 21 of 25
IF BOF()
GO TOP
SET MESSAGE TO "Top of the table"
ELSE
SET MESSAGE TO
ENDIF
If these changes are made to the navNext and navPrior classes, they will also apply automatically to the appropriate buttons in
vcr and vcr2.
Adding VCR to a Form Class
Once vcr is defined as a control, the control can be added in the definition of a container. For example, the following code added to
Navclass.prg defines a form with added navigation buttons:
DEFINE CLASS NavForm AS Form
ADD OBJECT oVCR AS vcr
ENDDEFINE
Running the Form Containing VCR
Once the form subclass is defined, you can display it easily with the appropriate commands.
To display the form
1. Load the class definition:
2. SET PROCEDURE TO navclass ADDITIVE
3. Create an object based on the navform class:
4. frmTest = CREATEOBJECT("navform")
5. Invoke the Show method of the form:
frmTest.Show
If you don’t call the SetTable method of oVCR (the VCR object in NavForm) when the user clicks the navigation buttons, the
record pointer moves in the table in the currently selected work area. You can call the SetTable method to specify what table to move
through.
frmTest.oVCR.SetTable("customer")
Note When the user closes the form, frmTest is set to a null value (.NULL.). To release the object variable from memory, use the
RELEASE command. Object variables created in program files are released from memory when the program is completed.
Defining a Grid Control
A grid contains columns, which in turn can contain headers and any other control. The default control contained in a column is a text
box, so that the default functionality of the grid approximates a Browse window. However, the underlying architecture of the grid
opens it up to endless extensibility.
The following example creates a form that contains a Grid object with two columns. The second column contains a check box to
display the values in a logical field in a table.
Grid control with a check box in one column
DEFINE CLASS grdProducts AS Grid Start the class definition and set properties that determine the
Left = 24 grid appearance.
Top = 10
Width = 295 When you set the ColumnCount property to 2, you add two
Height = 210 columns to the grid. Each column contains a header with the
Visible = .T. name Header1. In addition, each column has an independent
RowHeight = 28 group of properties that determines its appearance and
ColumnCount = 2 behavior.
Column1.ControlSource ="prod_name" When you set the ControlSource of a column, the column
Column2.ControlSource ="discontinu" displays that field’s values for all the records in the table.
Discontinu is a logical field.
Column2.Sparse = .F. Column2 will contain the check box. Set the column’s Sparse
property to .F. so that the check box will be visible in all rows,
not just in the selected cell.
Page 22 of 25
"Discontinued"
The following class definition is the form that contains the grid. Both class definitions can be included in the same program file.
Definition of a Form Class that Contains the Grid Class
Code Comments
DEFINE CLASS GridForm AS FORM Create a form class and add an object, based on the grid class,
Width = 330 to it.
Height = 250
Caption = "Grid Example"
ADD OBJECT grid1 AS grdProducts
PROCEDURE Destroy The program that creates an object based on this class will use
CLEAR EVENTS READ EVENTS. Including CLEAR EVENTS in the Destroy
ENDPROC event of the form allows the program to finish running when
the user closes the form.
ENDDEFINE End of the class definition.
The following program opens the table with the fields to be displayed in the grid columns, creates an object based on the GridForm
class, and issues the READ EVENTS command:
CLOSE DATABASE
OPEN DATABASE (HOME(2) + "data\testdata.dbc")
USE products
frmTest= CREATEOBJECT("GridForm")
frmTest.Show
READ EVENTS
This program can be included in the same file with the class definitions if it comes at the beginning of the file. You could also use the
SET PROCEDURE TO command to specify the program with the class definitions and include this code in a separate program.
Creating Object References
Instead of making a copy of an object, you can create a reference to the object. A reference takes less memory than an additional
object, can easily be passed between procedures, and can aid in writing generic code.
Returning a Reference to an Object
Sometimes, you might want to manipulate an object by means of one or more references to the object. For example, the following
program defines a class, creates an object based on the class, and returns a reference to the object:
*--NEWINV.PRG
*--Returns a reference to a new invoice form.
frmInv = CREATEOBJECT("InvoiceForm")
RETURN frmInv
ENDDEFINE
In the main program of your application, you could create an object based on the NewUserclass:
oUser = CREATEOBJECT('NewUser')
oUser.Logon
Throughout your application, when you need information about the current user, you can get it from the oUser object. For example:
IF oUser.GetAccessLevel( ) >= 4
DO ADMIN.MPR
ENDIF
Integrating Objects and Data
In most applications, you can best utilize the power of Visual FoxPro by integrating objects and data. Most Visual FoxPro classes
have properties and methods that allow you to integrate the power of a relational database manager and a full object-oriented system.
Properties for Integrating Visual FoxPro Classes and Database Data
Class Data properties
Because these data properties can be changed at design or run time, you can create generic controls with encapsulated functionality
that operates on diverse data.
Page 25 of 25