Chapter 16 Inheriting Forms and Creating Base Classes 407
Step 4: Create an object based on the new class
- Click the Form1 .vb icon in Solution Explorer, and then click View Designer.
The Form1 user interface appears.
- Double-click the Display Record button to open the Button1_Click event procedure in
the Code Editor. - Type the following program statements:
Dim Employee As New Person
Dim DOB As Date
Employee.FirstName = TextBox1.Text
Employee.LastName = TextBox2.Text
DOB = DateTimePicker1.Value.Date
MsgBox(Employee.FirstName & " " & Employee.LastName _
& " is " & Employee.Age(DOB) & " years old.")
This routine stores the values entered by the user in an object named Employee that’s
declared as type Person. The New keyword indicates that you want to immediately
create a new instance of the Employee object. You’ve declared variables often in this
book—now you get to declare one based on a class you created yourself! The routine
then declares a Date variable named DOB to store the date entered by the user, and the
FirstName and LastName properties of the Employee object are set to the first and last
names returned by the two text box objects on the form. The value returned by the
date/time picker object is stored in the DOB variable, and the final program statement
displays a message box containing the FirstName and LastName properties plus the age
of the new employee as determined by the Age method, which returns an integer value
when the DOB variable is passed to it. After you define a class in a class module, it’s
a simple matter to use it in an event procedure, as this routine demonstrates.
- Click the Save All button to save your changes, and then specify the
C:\Vb10sbs\Chap16 folder as the location. - Click the Start Debugging button to run the program.
The user interface appears in the IDE, ready for your input.
- Type a first name in the First Name text box and a last name in the Last Name text box.
- Click the date/time picker object’s arrow, and then scroll in the list box to a sample
birth date (the date I’m selecting is July 12, 1970).
Tip You can scroll faster into the past by clicking the Year field when the date/time picker
dialog box is open. Scroll arrows appear, and you can move one year at a time backward
or forward. You can also move quickly to the month you want by clicking the Month field
and then clicking the month name.