Jeff Webb, Mike McKelvy, Ronald Martinsen, Taylor Maxwell, Michael Regelski September 1995 Special Edition Using Visual Basic 4 - Chapter 5 1-56529-998-1 Computer Programming computer programming Visual Basic OLE database applications ODBC VB VBA API This book is an all-in-one reference that provides extensive coverage of every topic and technique for creating optimized and customized applications with Visual Basic.

Chapter 5

Using Visual Basic's Data and Bound Controls


Chapter 4, "Manipulating Data with a Program," introduced you to the data access objects and the way program commands are used to manipulate these objects. You learned that you can write powerful database applications using these methods. The discussions in Chapter 4 also provided a good basis for the discussion of the data and bound controls; these objects automate and simplify many of the data access tasks. With the improvements in the data control and the addition of more bound controls (these topics are discussed in this chapter), these controls provide an excellent means of developing data entry and data viewing programs for almost any need.

As good as the data control is, there are still occasions when the data control is not the right tool to use for your application. For example, you would not want to use it for an application that reads data directly from a COM port into the database. You will find, however, that the data control is a powerful tool for many applications, both by itself and in combination with the methods of the data access objects.

This chapter discusses how the data and bound controls are used. Also in this chapter, you build a data entry screen using many of the bound controls discussed. The data entry screen allows the user two views of the data: a single record view and a browse view, which allows editing of multiple records. The two views of the data entry screen are shown in figures 5.1 and 5.2.

Fig. 5.1

The sample data entry screen in single record mode.

Fig. 5.2

The sample data entry screen in browse mode for modifying data.

In this chapter, you learn about the following:

What's New in Version 4?

Visual Basic Version 4 offers some great improvements over Version 3 in the area of the data control and bound controls. These improvements dramatically extend their capabilities and overcome most of the deficiencies of the earlier version. For the data control itself, the key improvements are as follows:

The ability to create any of the recordset types is the most important of these three improvements. This ability allows you to set an index for a data control that uses a table type recordset, thus allowing the use of the Seek method to quickly find records. Being able to set indexes means that you can change the presentation order of the recordset more easily. Another advantage of being able to use tables is that any updates made by others in a multiuser environment are immediately available to the current user. This was not the case when the data control was limited to using dynasets only.

In addition to the improvements in the data control, Version 4 adds five new data-bound controls. These controls are listed here:

The differences between the two types of list and combo boxes are covered later in this chapter. The addition of these new controls greatly expands the flexibility of programs that can be developed with the bound controls.

Understanding the Data Control

The data control is designed to provide an easy means of access to a database. To use the data control, you follow these five steps:

  1. Select the control from the toolbox.
  2. Draw the control on your form.
  3. Set the DatabaseName property.
  4. Set the RecordSource property.
  5. Set the RecordsetType property.

At this point, you have created the links to the database and recordset with which you want to work. This method requires far less work than having to specify all the functions to do this with program code.

The data control also provides record-movement functions for your applications. The buttons on the data control take the place of command buttons that you would have to program and they perform the equivalent functions of the MoveFirst, MovePrevious, MoveNext, and MoveLast methods.

When setting up the data control, you typically set the DatabaseName and RecordSource properties at design time. However, you can also set properties at run time. It is also possible to create a recordset with the data access objects (see Chapter 4) and assign that recordset to a data control.

Looking at How the Data Control Works

The data control provides access to your data by creating a recordset based on the information in the database Name and RecordSource properties. The default recordset type is a dynaset, but you can also use a table or snapshot.


You cannot create a new table with the data control. You can only access an existing table in the database. However, if you specify the recordset type as table, you get all the advantages of using a table (as described in Chapter 4).

With the data control, you can create a dynaset (or snapshot) from a table, a query, or a SQL statement. You are not limited to using an Access database. You can use the data control and bound controls with any database files accessible through the Jet engine.

If you specify the properties of the data control at design time, the recordset is created when your form is loaded and the data control is displayed. If you specify (or subsequently change) the data control properties at run time, the new recordset is created when the properties are set.

Adding a Data Control to a Form

The first step in using a data control is to add the control to your application's form. To do this, first select the data control object from the Visual Basic toolbox (see fig. 5.3). Once selected, place and size the data control just as you do any other design object. After you set the desired size and placement of the data control on your form, you can set the Name and Caption properties of the data control.

Fig. 5.3

The data control is one of the tools in the Visual Basic toolbox.

The Name property sets the control name, which identifies the control and its associated data to the bound controls. The Name property is also the name of the recordset object that you use with any program commands that your application needs. The default name for the first data control added to a form is Data1. Additional data controls added to a form are sequentially numbered as Data2, Data3, and so on. You can change the name of the data control by selecting the Name property from the Properties window and typing the desired name.


You can quickly access the Properties window by pressing F4 or clicking the Properties icon on the toolbar.

The Caption property specifies the text that appears on the data control. You usually want the caption to be descriptive of the data the control accesses. The default for the Caption property is the initial setting of the Name property (for example, Data1 for the first data control). You can change the Caption property the same way you change the Name property.

For the examples in this chapter, add a data control with the name Items and the caption Retail Items. The form with this control added is shown in figure 5.4.

Fig. 5.4

Draw the data control on your form and set its caption to an expression meaningful to your application.

Setting the Properties

You attach a database and recordset to a data control by setting the properties of the control. The only two properties required are DatabaseName and RecordSource. These are the minimum specifications for using an Access database with the data control. Specifying these two properties defines the information you want in the data control and creates a dynaset with the default of nonexclusive, read/write access to the data. If you want to create a recordset other than a dynaset, you also must set the RecordsetType property.


The DatabaseName property is not the same as the Name property mentioned earlier. The Name property specifies the name of the data control object. This is used to reference the object in code. The DatabaseName property specifies the name of the database file that the data control is accessing.

The DatabaseName Property

For Access databases, the DatabaseName property is the name of the database file, including the full path name. You can enter the name by selecting the DatabaseName property from the Properties dialog box and either typing the database name or selecting the database from a list. Figure 5.5 shows the Properties dialog box with the DatabaseName property selected.

Fig. 5.5

Use the Properties dialog box to set the database name for the control.

To select the database name from the dialog box, click the ellipsis button (...) at the right of the property input line. This action displays a DatabaseName dialog box (see fig. 5.6). Select the filename you want and click OK. The selected filename then appears next to the DatabaseName property of the data control.

Fig. 5.6

You can enter a database name or choose it from the DatabaseName dialog box.

If you use the data control with databases other than Access, the DatabaseName property requires different values such as the path name for the data subdirectory. The required values for some common databases are summarized in table 5.1.

Table 5.1 DatabaseName Property Requirements for Various Database Types

Database Type Database Name Value
Access Name of database including path (d:\sub\name.MDB)
FoxPro Subdirectory path (d:\sub\) for database files
dBASE Subdirectory path (d:\sub\) for database files
Paradox Subdirectory path (d:\sub\) for database files
Btrieve Data definition file including path (d:\sub\name.DDF)

The RecordSource Property

After you designate the database to use with the DatabaseName property, specify the information you want from the database with the RecordSource property. If you are working with a single table as your recordset, you can enter the table name or select it from the list of tables (see fig. 5.7).

Fig. 5.7

You can select the RecordSource from a list of tables available in the database.

You can access only selected information from a table or use information from multiple tables by using a SQL statement. To use a SQL statement to define the recordset, you set the RecordSource property to the name of a QueryDef (which contains the SQL statement) in the database or enter a valid SQL statement in the property definition.. You can use any SQL statement that creates a dynaset (you can also include functions in your SQL statement). If you are using a QueryDef, it must be a QueryDef that has already been defined and stored in the database.

If you are using the data control to work with a nonAccess database, you must set the RecordSource property to the proper table name or SQL statement for that database. Again, if you are using only a table, you can select it from the drop-down list for the RecordSource property.

The RecordsetType Property

The default recordset type for a data control is a dynaset. If you need to create a snapshot or access a table directly, you must change the setting of the RecordsetType property. Do this by selecting the desired type from a drop-down list in the Properties dialog (see fig. 5.8).

Fig. 5.8

Use the RecordsetType property to determine whether the data control uses a table, dynaset, or snapshot.

The BOF and EOF Action Properties

The action properties tell the data control what to do when either the beginning-of-file (BOF) or end-of-file (EOF) is reached. For the BOF property, you have two choices:

For the EOF property, you have three choices:

The values of each of these properties can be chosen from a drop-down list in the Properties dialog box. The AddNew setting of the EOFAction property can be useful if you have an application that adds a number of new records. As with most other properties of the data control, these properties can be reset to other values at run time.


These BOF and EOF actions are triggered only when the beginning or end of the file is reached using the data control (in other words, pressing the next button). They have no effect if the beginning or end of file is reached using the data access methods in code (as in MoveNext).

Other Optional Properties

Four other properties can be set for the data control:

Table 5.2 Connect Property Settings for Various Database Types

Database Type Value of Connect Property
Access Access
FoxPro 2.0 FoxPro 2.0
FoxPro 2.5 FoxPro 2.5
FoxPro 2.6 FoxPro 2.6
dBASE III dBASE III
dBASE IV dBASE IV
Excel Excell
Paradox 3.x paradox 3.x;pwd=password
Paradox 4.x paradox 4.x;pwd=password
Btrieve btrieve
ASCII Text Text

I tried to set an index for my recordset using the Index property of the data control, but was unable to do so.

The Index property does not refer to a database index but to the index position in an array. A data control, like any other Visual Basic control object, can be part of a control array. If you have such an array, the Index property specifies the position of the current control in that array. Remember that a data control by default creates a dynaset—and you cannot apply an index to a dynaset. You can use an index if you specify that the data control should use a table, but the index can be set only with a program command such as this one:

Data1.Recordset.Index = "Price"

Setting Properties at Run Time

You can choose to set (or reset) the DataBaseName, RecordSource, and RecordsetType properties of the data control at run time. Following are three cases in which it is desirable to set the properties at run time.

You want to allow the user to select a specific database file from a group of related files. For example, a central office application keeps a separate database for each store of a chain; your application must allow the user to select the store with which he or she wants to work.

You want to allow users to set specific conditions on the data they want to see. These conditions may take the form of filters or sort orders (for example, show only salespeople with over $10,000 in sales in order of total sales). Alternatively, your application may have to set the filters as part of an access control scheme, such as allowing a department manager to see data about only the people in his or her department. In the case of the application setting the filters, the information is set at design time, but is incorporated in code instead of in the initial setting of the data control properties.

You want the user to specify the directory in a configuration file (or have your setup program do it for them) and then use the information from the configuration file to set your data control properties. If you are developing a commercial application, there is no guarantee that the user has the same directory structure you have. In fact, many users are annoyed if you impose a specific directory structure or drive designation as a requirement for your program.

If you need to set the parameters at run time, simply set the properties with code statements shown in listing 5.1. As shown in the listing, you must specify the name of your data control, the property name, and the desired property value.

After the properties have been set, use the Requery method of the data control to implement the changes. This method is shown in the last line of listing 5.1. The changes to the data control (that is, the creation of the new recordset) take effect after the Requery method is run.

Listing 5.1 Setting or Changing the DatabaseName and RecordSource Properties of a Data Control at Run Time

'*******************************************
'Set the value of the DatabaseName property
'*******************************************
Items.DatabaseName = "A:\TRITON.MDB"
'******************************************
'Set the value of the RecordSource property
'******************************************
Items.RecordSource = "Retail Items"
'*********************************************************
'Set the value of the RecordsetType property to table (0)
'*********************************************************
Items.RecordsetType = 0
'***********************************************
'Use the Requery method to implement the changes
'***********************************************
Items.ReFresh

Looking at Advantages of the Data Control

The key advantage to using the data control is that less programming is required to develop a data access application. You do not have to provide program code to open or create a database or recordset, to move through the records, or to edit the existing records in the recordset. The data control makes the initial application development much quicker and makes maintenance of your code much easier.

When using the data control, you also have the advantage of specifying your data objects (database and recordset) at design time, and you can select these options from dialog boxes and lists. Selecting options from lists cuts down on errors that can be introduced into the application by eliminating the typographic errors to which many developers (especially this author!) are prone.

The other advantage of the data control is that it provides a direct link to the data. You do not have to specifically invoke the Edit and Update methods to modify the data in the database. The advantage to you is that your changes show up in the database as soon as you enter them.

In addition to these advantages of using the data control, several of the bound controls that are new for Version 4 provide an easy way to accomplish tasks that are quite difficult using just the data access objects and program commands. These controls are the data bound list box, data bound combo box, and data bound grid. These controls are discussed in detail later in this chapter.

Looking at Limitations of the Data Control

As useful as the data control is, it also has a few limitations. (Doesn't everything?) These limitations are listed here:

Later in this chapter, you see how to overcome some of these limitations when you look at combining the data control with program code.

Understanding the Bound Controls

Bound controls are simply Visual Basic control objects that can be linked to fields in one or two data controls. In addition, the bound controls have a data-changed property that triggers a data-changed event in the data control. Visual Basic provides 13 bound controls:

These controls are called out on the Visual Basic toolbox shown in figure 5.9.

Fig. 5.9

There are 13 bound controls available in Visual Basic.

In addition, many vendors of third-party controls are making their controls data aware so that they can be used with the data control.

Looking at What the Bound Controls Do

The bound controls display the data from the field and data source specified in the control's properties. The data source for a bound control is always a data control. As the user moves from record to record using the data control, the bound controls are updated to reflect the contents of the current record. Table 5.3 lists the bound controls, the type of data they can handle, and the control property that displays the data.

Table 5.3 The Relationship between Bound Controls and Types of Data in the Underlying Recordset

Control Name Data Type(s) Control Property
Picture box Long Binary Picture
Label Text, Numeric, Date Caption
Text box Text, Numeric, Date Text
Check box True/False, Yes/No Value
Image Binary Picture
List box Text, Numeric, Date Text
Combo box Text, Numeric, Date Text
Data bound list box Text, Numeric, Date Text
Data bound combo box Text, Numeric, Date Text
Data bound grid Text, Numeric, Date Text, Value
Masked edit Text, Numeric, Date Text
3-D check box True/False, Yes/No Value
3-D Panel Text, Numeric, Date Caption

The bound controls also provide a direct link to the data in the recordset. Any changes made in the control are reflected in the recordset. There are no intermediate steps of setting the field value equal to the value of the control and updating the record.

Adding Bound Controls to a Form

To add one of the bound controls to your form, select the control from the toolbox and position and size the control on the form. Figure 5.10 shows a text box added to the form with the data control on it.

Fig. 5.10

You draw bound controls on your form just like any other control.


If you hold down the Ctrl key when you click on a control in the toolbar, you can add multiple controls of that type to your form. This eliminates the hassle of having to click on the control icon for each occurrence of the control that you add.

The Name property of the bound control defines the object by which the control is referenced in any program statements. If you are using only the data control, you may want to leave the Name property with its default value. If you are going to use program statements, you may want to change the name to one that has some meaning to you. The Name property does not affect how the bound control performs.

Setting the Properties of the Bound Controls

For a bound control to work with the data from a recordset, you must tie the bound control to the data control representing the recordset. Do this by setting the DataSource property of the bound control. Depending on the specific control used, you may have to set other properties. By working on the sample Retail Items data entry screen throughout the remainder of this chapter, you learn many of the bound controls, which properties must be set, and how to set them.

Setting the DataSource Property

To set the DataSource property, select the property from the Properties dialog box for your control. Click the arrow to the right of the input area to see a list of all the data controls on the current form. Select one of the controls from the list and the DataSource property is set. This procedure is shown in figure 5.11.


Double-clicking on the DataSource property will scroll through the list of available data controls.

Fig. 5.11

Select the DataSource for the bound control from the list of data controls on the form.

Using the Label and Text Box Controls

The label and text box controls are used for the display of any type of alphanumeric data. Use the text box control to edit any type of alphanumeric data; use the label control if you want to keep the displayed data from being updated. For both of these types of controls, you set the DataField property after you set the DataSource property. In the sample case, you want to allow editing of all the fields, so you do not use labels as bound controls. Figure 5.12 shows the data entry screen with the text boxes and unbound labels displayed.

Fig. 5.12

You can use the label and text box controls to display alphanumeric data.

To set the DataField property of the control, select the DataField property from the Properties dialog box, click the arrow to the right of the input area, and choose one of the fields from the displayed list. The list includes all available fields from the recordset defined in the specified DataSource (see fig. 5.13).

Fig. 5.13

Select the DataField for the bound control from the list of fields in the selected data control.


Double-clicking on the DataField property will scroll through a list of available fields.

Using the Picture Box and Image Controls

The picture box and image controls are used to display Windows graphics files (BMP, WMF, ICO, and DIB formats). When tied to a long binary field in a recordset, these controls can display and store photos, graph images, drawings, and so on in a database. To bind either of these control types to a recordset, set the DataSource and DataField properties as described in the preceding sections.

The main difference between the picture box and image controls is the way in which they display pictures. By default (Stretch property set to False), the image control changes size to fit the picture it contains. If you set the Stretch property to True, the image control changes the size of the picture to fit the control. This may change the aspect ratio (height to width ratio) of the picture and change its appearance. By default (Autosize property set to False), the picture box control displays as much of the picture as fits in the control without changing the aspect ratio. If you want to see the whole picture, set the Autosize property of the picture box to True, which causes the control to change size to fit the picture.

For the sample case, you want to display a picture of the fish in the inventory. Figure 5.14 shows a picture box added to the form and tied to the Photo field in the recordset.

Fig. 5.14

You can add pictures to your form and database with the picture or image control.

Unlike most other bound controls, the picture and image controls do not allow you to edit their contents directly. The best way to get a picture into the recordset is to use the LoadPicture function to retrieve a picture from a file and place it in the control (see listing 5.2). This capability is added to the sample case with the Add Photo button shown in figure 5.14. The Common Dialog control was added to the form to allow the user to select the file to import. The use of the Common Dialog button is also shown in listing 5.2.

Listing 5.2 Using the Common Dialog Control and the LoadPicture Function to Add a Picture to the Picture or Image Control and the Recordset

'**************************************************
'Use the Common Dialog to get the file name to load
'**************************************************
Getfile.Filter = "Bitmap Files (*.BMP)|*.bmp| All Files|*.*"
Getfile.DefaultExt = "BMP"
Getfile.ShowOpen
DataName = Getfile.FileName
'**************************************************************
'Use the LoadPicture function to add the picture to the control
'**************************************************************
Picture2.Picture = LoadPicture(DataName)

Using the Check Box Control

The check box control displays True and False information. The box is checked if the bound field has a True value; it is unchecked if the bound field has a False value. The check box is bound to the recordset by setting the DataSource and DataField properties.

Using the List Box and Combo Box Controls

The list box and combo box controls allow the user to choose one item from a list of items; in addition, the combo box allows the user to enter a different item. These controls in Visual Basic 4 are enhancements of the controls available in the previous versions of Visual Basic. The enhancement allows you to bind the control to a data field to store the user's choices in a field. You do this by setting the DataSource and DataField properties of the control. To give your user a list of items from which to select, you use the AddItem method of the control. For the sample case, use a combo box to allow users to select the product category for the item they are editing (see fig. 5.15). Listing 5.3 shows the population of the list.

Fig. 5.15

Use a list or combo box to present your user with a list of choices.

Listing 5.3 Populating the List with the AddItem Method

Combo1.AddItem "Aquariums"
Combo1.AddItem "Fish - FW"
Combo1.AddItem "Fish - SW"
Combo1.AddItem "Plants"
Combo1.AddItem "Supplies"

Using the Data Bound List Box and Data Bound Combo Box

The data bound list box and combo box are similar in function to their standard counterparts. They are designed to present the user with a list of choices. The key difference is that the data bound list and combo box controls get their list information from a recordset instead of from a series of AddItem statements.

Consider an example from the sample case. As your users enter data about a product, you want them to also tie the product to a supplier. One of the tables in the database contains supplier information. You can use the data bound list box to allow your users to select a supplier from those contained in the supplier table. The data bound list takes the supplier ID selected from the Supplier table and stores it in the appropriate field of the Retail Items table. You may think it would be hard to select the appropriate supplier if all you can see is the ID. However, the data bound list and combo boxes allow you to select a second field from the source table to serve as the display in the list. This means that you can display the name of the supplier in the list box but store only the supplier ID in the Retail Items table. This concept is shown graphically in figure 5.16.

Fig. 5.16

The data bound list and combo boxes let you pick an item from one table for inclusion in another table.

You set up the data bound list or combo box by specifying five properties. These properties are described in table 5.4.

Table 5.4 Properties for Data Bound List Box or Combo Box

Property Sample Case Setting Description
RowSource Suppliers The name of the data control containing the information used to populate the list.
BoundColumn SupplierID The name of the field containing the value to be copied to the other table.
ListField Name The name of the field to be displayed in the list.
DataSource Items The name of the data control containing the recordset that is the destination of the information.
DataField SupplierID The name of the destination field.

You can set each of these properties by selecting the property from the Properties dialog box and choosing the setting from a drop-down list. Several notes must be considered when setting the properties of the data bound list and combo boxes:

Figure 5.17 shows the data bound list box added to the sample data entry form.

Fig. 5.17

A data bound list box added to the screen to allow the user to select from a list of suppliers.

Using the Data Bound Grid

The data bound grid provides a means to view the fields of multiple records at the same time. The data bound grid is similar to the table view used in Access or the Browse command used in FoxPro. The data bound grid displays information in a spreadsheet style of rows and columns. It can be used to display any alphanumeric information or pictures.

To set up the data bound grid, you only need to specify the DataSource property to identify the data control containing the data. Once this is set, the grid displays all fields of all records in the recordset. If the information is larger than the area of the grid you defined, scroll bars are presented to allow you to view the remaining data.


To conserve resources used by your application, use a QueryDef or SQL statement in the RecordSource property of the data control that the grid will use. This allows you to keep to a minimum the number of records and fields handled by the grid.

Your user can select a grid cell to edit by clicking on the cell with the mouse. To add a new record, the user positions the pointer in the last row of the grid indicated by an asterisk (*) and enters the desired data. You must specifically allow editing and record addition in the grid by setting the AllowAddNew and AllowUpdate properties of the grid to True.

For the sample case, use the data bound grid to display the Retail Items information in a browse mode. To save screen real estate, allow the user to switch between the browse mode and single-record mode by using the command button at the bottom right corner of the screen. The data bound grid for the sample case is shown in figure 5.18.

Fig. 5.18

You can use the data bound grid to display information from several records at once.

Knowing When to Use the Data Control and When to Use Code

As part of your application design, you must determine whether to use only the data control, only code statements, or a combination of both. The following sections examine types of programs that lend themselves to each type of programming. These are not hard-and-fast rules for development but merely examples of the uses of the various programming techniques.

Using the Data Control Alone

You may want to use the data control by itself for applications in which the user access is read only or when there is no need to add or delete records. In these cases, you don't need anything beyond the capabilities of the data control—and the ease of programming makes it an excellent choice.

The data control is also great for prototyping an application. With it, you can rapidly develop data forms and see how your data will appear. Prototype applications can be shown to a client, and adjustments or improvements can be made very quickly. (Clients are usually really impressed by prototypes.) Once the prototype is developed, you can keep the data control as the basis of your application and enhance its functionality using some additional program code. You may, however, decide to write the entire application in program code. In this case, the prototype you developed provides a detailed model from which you can work.

A more unusual application is to provide global information about a database. Suppose that you have an engineer who wants to see the statistical variation of a set of experimental data. You could write the SQL statement of your data control's RecordSource to return the minimum, maximum, and average values of the data as well as the standard deviation. These returned fields could then be bound to a set of controls for display on the form. Because only one record is returned, you may choose to hide the data control to keep the form cleaner. In this case, the bound controls make the display of the data easier than if you were working with a program.

Using a Program Alone

It is better to use a program alone when much of the data entry is done by other programs or equipment. Also, for a heavily used multiuser system, the data control may not be the best choice of techniques.

For unattended data entry from another program or from an instrument, the data control is inappropriate because it is designed only to respond to user input events. The data control performs updates only when the record movement buttons are pushed or when the data control is closed. A program, on the other hand, can be set up to read files for input on a timed basis or to read data directly from a serial port and add it to the database.

For heavily used multiuser applications, a data control may increase the possibility of record-locking conflicts because the control of the locking is not as fine as in a "program command only" application. Also, transaction processing is not as easily implemented with the data control.

Using the Data Control in Combination with a Program

Probably the best solution for many applications is to use the data control in combination with program commands. You can use the program commands to enhance the basic functionality of the data control by including such features as these:

The next section looks at examples of some of these functions.

Enhancing the Data Control

As flexible as the data control is, it lacks a few functions that are necessary for most data entry applications. These functions were listed in the preceding section. To overcome these shortcomings, you can add the functions to the data entry screen using program commands assigned to either a command button or to events of the data control and bound controls.

Adding Record Addition and Deletion Capabilities

The next step in developing the sample application is to add the ability to add and delete records. To do this, add two command buttons to the form named Add and Delete. To make the buttons functional, add the code segments shown in listing 5.4 to the click event of the appropriate button.

Listing 5.4 Program Statements Placed in the Click Event of Command Buttons to Add Capabilities to the Data Entry Screen

'*****************************************************************
'Command to add a new record,
‘place in click event of Add button
'*****************************************************************
Items.Recordset.AddNew
'*****************************************************************
'Commands to delete a record,
‘placed in click event of Delete button
'*****************************************************************
Items.Recordset.Delete
Items.Recordset.MoveLast

As you can see, this listing did not enter a command to invoke the Update method (updates are done automatically by the data control whenever you move to a new record or close the form).


The move command was added to the Delete button to force a move to a new record. After a record is deleted, it is no longer accessible but still shows on the screen until a move is executed. If you did not force a move and tried to access the deleted record, an error would occur.

The data entry form now looks like the one shown in figure 5.19.

Fig. 5.19

New capabilities added to the data entry screen by adding command buttons and using program commands.

Finding a Specific Record

Another enhancement to the capabilities provided by the data control is the ability to search for a specific record. To add this feature, you must use either the Find method or the Seek method of the data control recordset, depending on the recordset type. For a table, use the Seek method; for a dynaset or snapshot, use the Find method. To implement the search, add a command button to the form. This command button invokes a dialog box that requests the ID to be found and then uses the appropriate method to perform the search (see listing 5.5).

Listing 5.5 Use the Seek or Find Method to Search for a Specific Record

'***************************************************************
'The variable SrchCond contains the value of the search criteria
'***************************************************************
If Items.RecordsetType = 0 Then
Items.Recordset.Seek ">=", SrchCond
Else
Items.Recordset.FindFirst "Items.Recordset([Item Code]) >= " _
& SrchCond
End If

Linking In Other Data

Earlier in this chapter, when you used the data bound list box, you made a link between the data in two tables. Suppose that you also want to display the name of the contact person at the supplier. You already have a data control that provides access to the supplier table, so you only have to display the data and maintain a link between the two tables.

To make the link work on the form, add a text box to the form that shows the supplier ID from the Retail Items table. Then, in the change event of the text box, add the search code shown in listing 5.6. This code takes the supplier ID from the text box and uses the FindFirst (or Seek) method on the supplier data control to find the correct record. When the pointer moves in the supplier table, the name of the contact person on the screen is updated.

Listing 5.6 Maintaining the Link between the Retail Items and Supplier Tables in the Change Event of the Supplier ID Text Box

'*********************************************************
'Set the find criteria to the text value of the text box.
'This value is the SupplierID from the Retail Items table.
'*********************************************************
FndCrit = "SupplierID = '" + Text8.Text + "'"
'******************************************************
'Execute the Find method to locate the proper supplier.
'******************************************************
Supplier.Recordset.FindFirst FndCrit

Using Multiple Data Controls

The last addition to the data entry screen (in the preceding section) raises some interesting programming points. First, you added another data control to the form. One obvious question is, "Why didn't you just include the additional fields in a SQL statement to generate the recordset for the original data control?" This could have been done using the following statement:

SELECT [Retail Items].*, Supplier.Contact FROM [Retail Items], _
Supplier
WHERE [Retail Items].SupplierID = Supplier.SupplierID

The advantage of doing this is that you wouldn't have to go through the trouble of establishing the Retail Items and Supplier link using the supplier ID text box and the change event. The downside of using the SQL statement is that the supplier information could have changed. Because you cannot set read-only properties for individual fields in the data controls recordset, you cannot prevent the update of the text boxes.

By using two data controls, you were able to protect the data in the Supplier table from unwanted changes. Another reason for using the two controls is that you can add controls to the form to switch between the Retail Items view and a Supplier view. Then you need the supplier data control to navigate through the recordset.

The other point illustrated by adding the supplier contact information is that other events can be used to change or affect the data control.


The validate event is triggered any time the record pointer is moved to a new record, an update is issued, or the database or form is closed. The validate event passes variables that tell what action triggered the event and whether any data in the current bound controls has been changed. By placing program code in the validate event, you can perform data checking in addition to engine-level data validation. You can also perform transaction processing with code in the event. It is not required that any code be put in the validate event; it is an optional feature. For the sample case, you do not to include any code in the validate event.

The data entry screen you built in this chapter is contained on the companion disk as CHAPTER5.MAK. Running this application allows you to see the data control and the bound controls in action.

From Here...

Some of the topics mentioned in this chapter are covered in greater detail in other portions of the book. Please refer to these chapters for more information:


© 1996, QUE Corporation, an imprint of Macmillan Publishing USA, a Simon and Schuster Company.