You are on page 1of 24

Visual Basic 5

Programming - 8
A Specialised Training Course
Contents

DATABASE OVERVIEW ................................................................................................................................... 2

INTRODUCING THE DATA CONTROL ........................................................................................................ 2


DYNASET DEFINITION .............................................................................................................................................. 3
DATA CONTROL PROPERTIES................................................................................................................................... 3
DatabaseName property .................................................................................................................................... 3
RecordSource property ...................................................................................................................................... 3
Exclusive property ............................................................................................................................................. 4
ReadOnly property............................................................................................................................................. 4
Connect property ............................................................................................................................................... 4
Database Property............................................................................................................................................. 5
Recordset property............................................................................................................................................. 5
Options property ................................................................................................................................................ 6
DATA CONTROL EVENTS ......................................................................................................................................... 7
Reposition Event ................................................................................................................................................ 7
Validate Event.................................................................................................................................................... 7
Error Event ........................................................................................................................................................ 8
DATA CONTROL METHODS ...................................................................................................................................... 8
Refresh Method .................................................................................................................................................. 8
UpdateControls Method .................................................................................................................................... 8
UpdateRecord Method....................................................................................................................................... 8
SETTING UP BOUND CONTROLS.................................................................................................................. 9
DataSource Property ......................................................................................................................................... 9
DataField Property............................................................................................................................................ 9
Using Bound Controls ....................................................................................................................................... 9
THE VISUAL DATA MANAGER APPLICATION ....................................................................................... 10

OBJECTS USED IN DATA ACCESS .............................................................................................................. 11


DATABASE OBJECT................................................................................................................................................ 12
Properties ........................................................................................................................................................ 12
Methods............................................................................................................................................................ 12
TABLEDEF OBJECT ................................................................................................................................................ 13
Properties ........................................................................................................................................................ 13
Methods............................................................................................................................................................ 13
DYNASET OBJECT.................................................................................................................................................. 14
Properties ........................................................................................................................................................ 14
Methods............................................................................................................................................................ 14
TABLE OBJECT ...................................................................................................................................................... 15
Properties ........................................................................................................................................................ 15
Methods............................................................................................................................................................ 15
FIELD OBJECT........................................................................................................................................................ 16
Properties ........................................................................................................................................................ 16
Methods............................................................................................................................................................ 16
SNAPSHOT OBJECT ................................................................................................................................................ 17
Properties ........................................................................................................................................................ 17
Methods............................................................................................................................................................ 17
INDEX OBJECT ....................................................................................................................................................... 18
Properties ........................................................................................................................................................ 18
Methods............................................................................................................................................................ 18
EXERCISES........................................................................................................................................................ 19

Visual Basic Book 8 © Mark Collins 1999 Page 1


Database Overview
In Visual Basic there are several possibilities for accessing data contained in database files of
various formats. The coding required for each, ranges from the relatively simple use of the
Data Control for manipulating MS-Access tables to more complex management of ODBC
links to client-server databases (Oracle, Informix, etc.).
This booklet will concentrate on the Data Control and the Objects involved.

Introducing the Data Control


The Data Control is provided with both editions of Visual Basic 5. As with most other
controls it consists of a number of properties, events and methods, many of which are
standard.
The Data Control can be used to manipulate data from the following databases...
• Microsoft Access 2.0 & 7.0
• FoxPro 2.0 - 3.0
• dBase III - V
• Paradox 3.x - 5.0
• ODBC
It operates as an ‘interface’ between other controls and the database. These other controls are
known as bound controls, only certain controls can be bound, these will be looked at in more
detail later.
These controls, when placed on the same form as a Data Control are linked to a specific field
in the Data Control’s Dynaset.
Recordset
A Recordset is a term used extensively in Data Access using Visual Basic. It refers to a two-
dimensional structure consisting of records (rows) and columns (fields). There are three
object types that have this structure...
• Tables
• Dynasets
• Snapshots
• Forward-Only
• Dynamic
Tables are familiar structures to any database practitioner, Dynasets and Snapshots are
similar to temporary tables and can consist of data extracted from several tables using a
QueryDef. We shall not be looking at the Forward-Only and Dynamic types.

Visual Basic Book 8 © Mark Collins 1999 Page 2


Dynaset definition
A Dynaset is a type of recordset that is the result of a query and that can have updatable
records. Like a Table, a Dynaset has records (rows) and fields (columns). A Dynaset is a
dynamic set of records you can use to add, change, and delete records from the underlying
table or tables and can contain fields from one or more tables in a database.
A data control opens a Database and then creates a Dynaset, using the RecordSource
property. The RecordSource property can be the name of a Table or QueryDef in the
Database, or it can be an SQL statement

Form
Bound Control
Data Control

Table 1
DYNASET
Database

Data Control Properties


The Data Control has several standard properties such as Enabled, Visible, FontName,
Height, Width etc.; it also has specific properties to control data access.

DatabaseName property
Determines the name and location of the source of data for a data control.
datactrl.DatabaseName = path
For Access databases, the DatabaseName property is the path and name of the database file
(.MDB ). For dBASE III, dBASE IV, Paradox, and FoxPro databases, the DatabaseName
property setting is the path to the directory of the database file (.DBF, .PDX).

RecordSource property
Once the DatabaseName property has been set this property then specifies the underlying
table, SQL statement, or QueryDef for the data control to create its Dynaset.
datactrl.RecordSource = {tablename | sqlstatement | queryname}
The Dynaset is then the source of the records accessible through bound controls on your
form.
Note: Both of the above properties are available at Design- and Run-time. If the values are
changed at Run-time the change must be registered using the Refresh Method.

Visual Basic Book 8 © Mark Collins 1999 Page 3


Exclusive property
Determines whether the underlying database for a data control is opened for single-user or
multi-user access.
datactrl.Exclusive = {True | False}

Setting Description
True The database is open for single-user access. No one else can open the database until it is closed.
False (Default) The database is open for multi-user access. Others can open the database and have
access to the data while it is open.

ReadOnly property
Determines whether the control's Database is opened for read-only access.
datactrl.ReadOnly = {True | False}
Setting Description
True The control's Database is opened with read-only access to data. Changes to data are not allowed.
False (Default) The control's Database is opened with read/write access to data.

This property is used only the first time a database is opened by your application. If your
application subsequently opens other instances of the database, the property is ignored. For a
change in this property to take effect, you must close all instances of the database and then
use the Refresh method.

Connect property
Used to set the Data Control to access a database other than Microsoft Access.
datactrl.Connect [ = connectinfo ]
You can use the DatabaseName, Exclusive, ReadOnly, and Connect properties to open a
database with a data control. For example, a data control uses these property settings to open
a Paradox database:
Data1.DatabaseName = "C:\PDX\PUBS"
Data1.Exclusive = True
Data1.ReadOnly = False
Data1.Connect = "Paradox;"

Visual Basic Book 8 © Mark Collins 1999 Page 4


Database Objects:
The following properties relate to objects for which we can declare variables of that type, just
as we could create variables of type Form and TextBox. We shall return to these in more
detail later.

Database Property
To provide access to data, a data control finds the specified database and then using the
Exclusive, ReadOnly, and Connect properties, opens it as a Database object. The Database
property is a direct reference to that object.
datactrl.Database.method
datactrl.Database.property = value
Database objects have properties and methods you can use to manage your data. You can use
any methods of a Database object with the Database property of a data control, such as Close
and Execute.

Recordset property
The Dynaset defined by a data control's Connect, DatabaseName, and RecordSource
properties.
datactrl.Recordset.property = value
datactrl.Recordset.method
The Recordset property is a reference to the underlying database object of a data control. It
has all the same properties and methods of the Dynaset object it represents.
The following example shows how you can combine the RecordCount property of a Dynaset
with the Recordset property to display the number of records in a data control's recordset:
Data1.Recordset.MoveLast
MsgBox "Records: " & Data1.Recordset.RecordCount

Visual Basic Book 8 © Mark Collins 1999 Page 5


Options property
Determines one or more characteristics of the Dynaset in the control's Recordset property.
Read/write at design time and run time.
datactrl.Options = Value
Where the value can be an expression based on...
Constant Value Description
1 In a multiuser environment, others cannot make changes to records in
dbDenyWrite the Dynaset.
4 You cannot make changes to records in the Dynaset.
dbReadOnly
8 You can add new records to the Dynaset, but you cannot read existing
dbAppendOnly records.
16 Updates can apply to all fields of the Dynaset, even if they also affect
dbInconsistent other records in the Dynaset.
32 (Default) Updates apply only to those fields that will not affect other
dbConsistent records in the Dynaset.
64 When using data controls with an SQL statement in the RecordSource
dbSQLPassThrough property, sends the SQL statement through to an ODBC database, such
as a SQL Server or Oracle database for processing.

To set more than one value for this property, you can combine them by adding values
together. For example, to set both dbReadOnly and dbInconsistent you could use this code:
Data1.Options = dbReadOnly + dbInconsistent
If you change this property at run time, you must use the Refresh method for the change to
have any effect.
To determine if the property contains a specific value, you can use the And operator. For
example, to determine if the recordset is opened for read-only access, you could use this
code:
If Data1.Options And dbReadOnly Then...

Visual Basic Book 8 © Mark Collins 1999 Page 6


Data Control Events
In addition to the usual events, the following three are exclusive to Data Controls.
• Reposition
• Error
• Validate

Reposition Event
Occurs after a record becomes the current record. When a data control loads, it makes the
first record in the recordset the current record, causing the Reposition event. Whenever a
user clicks any button on the data control, moving from record to record, the Reposition event
occurs after each record becomes current. In contrast, the Validate event occurs before
moving to a different record.
You can use this event to perform calculations based on data in the current record, or to
change the form in response to data in the current record.

Validate Event
The Validate event occurs before a different record becomes the current record. The
following line illustrates the declaration line of the event procedure.
Sub datacontrol_Validate ( Action As Integer, Save As Integer)
The Action argument indicates the operation that is causing this event to occur. The possible
values are...
Constant Value Description
rdDataActionCancel 0 Cancel the operation when the Sub exits.
rdDataActionMoveFirst 1 MoveFirst method.
rdDataActionMovePrevious 2 MovePrevious method.
rdDataActionMoveNext 3 MoveNext method.
rdDataActionMoveLast 4 MoveLast method.
rdDataActionAddNew 5 AddNew method.
rdDataActionUpdate 6 Update operation (not UpdateRecord).
rdDataActionDelete 7 Delete method.
rdDataActionFind 8 Find method.
rdDataActionBookmark 9 The Bookmark property has been set.
rdDataActionClose 10 The Close method.
rdDataActionUnload 11 The form is being unloaded.

The Save argument initially indicates whether bound data has changed (True/False).
You can use this event to change values and update data as necessary. You can also choose to
save data or not, and choose to stop whatever action is causing the event to occur and
substitute a different action.

Visual Basic Book 8 © Mark Collins 1999 Page 7


Error Event
Occurs only as the result of a data access error that occurs when no Visual Basic code is being
executed.
Sub datacontrol_Error (DataErr As Integer, Response As Integer)
Where DataErr is the error number and Response is a number corresponding to the response
you want to take as represented by...
Constant Value Description
rdDataErrContinue 0 Continue
rdDataErrDisplay 1 (Default) Display the message

You ordinarily provide error-handling functionality for run-time errors in your code.
However, run-time errors can occur when none of your code is running, such as...
• A user clicks a data control button.
• The data control automatically opens a database and loads a recordset after the
Form_Load event.
• A custom control performs an operation such as the MoveNext method, the
AddNew method, or the Delete method.

Data Control Methods


There are many methods that we will use, but most do not directly belong to the Data Control.
Most methods used in data access (such as MoveNext) are part of an object (such as a
Database Object) linked to the data control. The methods that are part of the control are...

Refresh Method
You can use the Refresh method on a data control to open or reopen the database (if the
DatabaseName, ReadOnly, Exclusive, or Connect properties have changed) and rebuild the
Dynaset in the control's Recordset property.

UpdateControls Method
Use this method to restore the contents of bound controls to their original values, such as
when a user makes changes to data and then decides to cancel the changes. This method
creates the same effect as making the current record current again, except that no events
occur.

UpdateRecord Method
Use this method to save the current contents of bound controls to the database during the
Validate event without triggering the Validate event again.

Visual Basic Book 8 © Mark Collins 1999 Page 8


Setting up Bound Controls
As mentioned earlier the Data Control is only one part of the chain. It links Databases via the
Dynaset that the control creates to bound controls. These bound controls reflect the contents
of a field in the Dynaset. The controls that can be bound in this way are...
• text boxes*
• labels*
• check boxes*
• images*
• picture boxes*
• masked edit*
• DBList boxes**
• DBCombo boxes**
• DBGrids and MSFlexGrids**
• other 3rd party controls
* - component can only display one field at a time.
** - component can display multiple records and/or fields.

To bind a control it must be placed on the same form as a Data Control. Once that Data
Control has been linked (i.e. DatabaseName and RecordSet properties set) the bound control
can then be linked. This is done by setting the following properties...

DataSource Property
Determines the data control through which the current control is bound to a database and can
only be set at design time. To complete the connection with a database, you must also set the
DataField property...

DataField Property
control.DataField = fieldname
The DataField property specifies a valid Field object name in the data control's Recordset
property and can be set at run-time as well as at design time. If set at design time then a list of
valid field objects is available.

Using Bound Controls


Once the Data Control and its bound controls have been set up then they are ready to use. As
you use the buttons on the Data Control to move through the records in the Dynaset the
contents of the fields are displayed in the bound controls. If the contents of the control are
editable (e.g. a TextBox) then the data in the Dynaset can be edited (permissions allowing).

Visual Basic Book 8 © Mark Collins 1999 Page 9


The Visual Data Manager Application
The impression you may have obtained so far is that if we need to create new Databases then
we require the relevant package (Access, Paradox, dBase etc.). This is not the case, Visual
Basic 5 provides an application called the Visual Data Manager. This can be accessed via the
Add-Ins / Visual Data Manager menu option.
The Visual Data Manager allows you to create new databases and examine or map the
structure of existing external databases in a variety of formats. Formats that you can either
create or modify with the Visual Data Manager are as follows...
Database Format Create Modify
Microsoft Access 2.0 Yes Yes
Microsoft Access 7.0 Yes Yes
Paradox 3.x - 5.0 Yes * Yes
dBASE III - V Yes * Yes
FoxPro 2.0 - 3.0 Yes* Yes

* - These external databases exist as directories on your disk. To create databases in these
formats, use Explorer to create a directory that becomes the database. Once the database
directory is created, use the Visual Data Manager to add tables and indexes, which become
files in this directory.
Once the Visual Data Manager is open you can either create an Access database (v2.0 or v7.0)
or open an existing database in any of the formats listed above. Once in you can create new
tables and indexes, add data to a table, change or examine the structure of a table or delete a
table. The two windows in the data manager are Database Window and SQL Statement; the
Database Window has the tree structure properties that can be doubled clicked with the
mouse to expand/collapse the default options. Also right clicking with the mouse over the
properties and choosing New Table brings up the Table Structure window where we can
add, modify or delete table and index details in our database.
The Visual Data Manager provides simple administration of our database, but be aware that
deleting tables, fields, indexes from the database schema are permanent and it is essential that
copies or backups of the schema are made first before attempting to modify the schema. If
you do not heed this warning, then significant data loss can occur with no way of retrieving
the existing data; this means that vital information could be lost and cause the business to
have substantial losses or even to collapse or cease trading.

Visual Basic Book 8 © Mark Collins 1999 Page 10


Objects used in Data Access
As mentioned earlier there are a number of objects related to this area that can be used for
greater control. Each object has its own set of properties and methods and in the Professional
Edition can have object variables declared of their type. The objects we are concerned with
are...
• Database Object
• Dynaset Object
• Snapshot Object
• Field Object
• Table Object
• TableDef Object
• Index Object
Just as Visual Basic maintains a collection of Forms (useful when we loose our object
variables for them) it also maintains the following collections...
• Fields Collection
• Indexes Collection
• TableDefs Collection
A Database object has a number of other data access objects, such as TableDef objects, Field
objects, and so on. Each object has a set of properties and methods, and some objects have
properties that are collections of other objects. In the same way that a form has a Controls
collection, a Database has a TableDefs collection of TableDef objects, and a TableDef has a
Fields collection of Field objects.

Database

TableDefs Collection

TableDef Object
Fields Collection Indexes Collection

Field Object Index Object

Visual Basic Book 8 © Mark Collins 1999 Page 11


For example, to set the value of the "PubID" Field in the current record of a data control's
Recordset property, you could use this code:
Data1.Database.TableDefs("Publishers").Fields("PubID").Value = 99
With the Professional Edition, you can create object variables of any of the object types using
the Dim and Set statements. For example, the following code creates object variables for a
Database, a Dynaset, and a Field:
Dim MyDb As Database, MyDn As Recordset, MyFd As Field
Set MyDb = OpenDatabase("BIBLIO.MDB")
Set MyDn = MyDb.OpenRecordset(dbOpenDynaset,"SELECT * FROM
Authors")
Set MyFd = MyDn.Fields("Au_ID")
You can use object variables and other Data Definition Language (DDL) features to modify
the structure of your database. For example, you can add a new Field to an existing table with
the following code:
Dim MyDb As Database, MyFd As New Field
Set MyDb = OpenDatabase("BIBLIO.MDB") ' Open database.
MyFd.Name = "Address" ' Set Field properties.
MyFd.Type = dbText
MyFd.Attributes = dbUpdatableField
MyDb.TableDefs("Authors").Append MyFd ' Append to TableDef.
This code creates a New object variable for a Field, sets the appropriate properties, then adds
it to a TableDef with the Append method. Since a TableDef contains the definition of a
Table, the Table now has a Field named "Address" ready for entering data. In much the same
way, you can create new tables and new indexes.

Database Object
A database object is a logical representation of a physical database. In the Standard Edition
you can only access such an object using the Database property of a data control. In the
Professional Edition you can also create object variables of its type using Dim and Set.

Properties
CollatingOrder Connect Exclusive
Name QueryTimeout TableDefs (coll)
Transactions Updatable (sic)

Methods
BeginTrans Close CommitTrans
CreateDynaset CreateQueryDef CreateSnapshot
DeleteQueryDef Execute ExecuteSQL
ListFields ListTables OpenQueryDef
OpenTable Rollback

Visual Basic Book 8 © Mark Collins 1999 Page 12


TableDef Object
An object in a database that defines the structure of a table. In contrast, a Table is the physical
container of the data in a Database.
With a data control, you can examine the structure of a table using the TableDefs collection
of the data control's Database property. For example, you can read the Count property of the
Fields collection to determine how many Field objects are in a Table, and then read the Field
names. For example, the following code prints all Field names in a TableDef:
Dim I
For I = 0 to Data1.Database.TableDefs("Pubs").Fields.Count - 1
Print Data1.Database.TableDefs("Pubs").Fields(I).Name
Next I

A table is stored in a database and has a name that is recognised by the database. A TableDef
has a Name property that is the name of the table defined by the TableDef and is not the same
as the name of an object variable to which it is assigned.
In the Professional Edition, you can create an object variable of type TableDefs as well as
type TableDef. You can make changes in the structure of a table, and even create new tables
in a database.

Properties
Attributes Connect DateCreated
Fields (coll) Indexes (coll) LastUpdated
Name SourceTableName Updatable

Methods
Append* Delete*
* these methods relate to a collection of TableDefs.

Visual Basic Book 8 © Mark Collins 1999 Page 13


Dynaset Object
An object representing a type of recordset that is the result of a query and that can have
updateable records. A Dynaset can contain fields from one or more tables in a database.
Many relational database systems allow similar structures, such as temporary tables, but do
not allow you to change the underlying data as you can with a Dynaset; it is a dynamic set of
records you can use to add, change, and delete records from the underlying table or tables.
Not all Fields can be updated in all Dynasets. Use the Updatable property of a Field to
discover if it is updatable.
A Dynaset we have already encounteresd is the RecordSet property of a Data Control.
In a multiuser environment, various users can open Dynasets referring to the same records.
Because a Dynaset is dynamic, when one user changes a record, other users have immediate
access to the changed data. If a user adds a record, the change is not reflected for any other
user until the other user's Dynaset is recreated using the Refresh method. If a user deletes a
record, other users are notified when they try to access that record. To maintain the integrity
of your data, records are locked during Edit and Update operations so that several users can't
update the same record at the same time.
In the Professional Edition, you can also declare an object variable as a Recordset type. To
create a Dynaset for an object variable, you would use the dbOpenDynaset method on a
Database or another Dynaset. You can have more than one object variable that refers to the
same set of records.

Properties
BOF Bookmark Bookmarkable
DateCreated EOF Fields (coll)
Filter LastModified LastUpdated
LockEdits Name NoMatch
Sort Transactions Updatable

Methods
AddNew Clone CreateDynaset
CreateSnapshot Delete Edit
FindFirst FindLast FindNext
FindPrevious ListFields MoveFirst
MoveLast MoveNext MovePrevious
Update

Visual Basic Book 8 © Mark Collins 1999 Page 14


Table Object
A table is a type of recordset that is a part of a Database and contains data about a particular
subject. A Table object is a logical representation of a physical table. Like all recordsets, a
table has records and fields.
With a data control, you can open a table only by setting the control's RecordSource property
to the name of the table. When the data control loads, it creates a Dynaset based on the single
table. Table objects can be used only in the Professional Edition. You can, however, access
the data in a table through the Dynaset created by a data control and represented by its
Recordset property.
The Name property of a Table object is not the same as the name of an object variable to
which it is assigned.
You can declare an object variable as a Table type. To open a Table with an object variable,
use the dbOpenTable method on a Database. You can have more than one object variable
that refers to the same table, and you can have one or more Dynasets that refer to some or all
fields and some or all records in one or more tables.
Information about the structure of a table, such as the name and field data type of each Field,
is stored in a TableDef.

Properties

Methods
AddNew Close CreateDynaset
CreateSnapshot Delete Edit
FindFirst FindLast FindNext
FindPrevious ListFields ListIndexes
MoveFirst MoveLast MoveNext
MovePrevious Seek Update

Visual Basic Book 8 © Mark Collins 1999 Page 15


Field Object
A part of a recordset that defines one ‘column’ of data. The Value property of a Field object
contains data from a single element of that column from the current record. Field objects are
stored with a TableDef in a Database.
The Name property of a Field object is not the same as the name of an object variable to
which it is assigned. Unlike forms and controls, the Name property of data access objects is
available at run time.
In the Professional Edition, you can declare an object variable as type Fields (a collection), or
as a type Field. You could use this code to print out the value of the "PubID" Field for each
record in a Dynaset...
Dim MyDb As Database, MyDn As Recordset, MyFd As Field
Set MyDb = OpenDatabase("BIBLIO.MDB")
Set MyDn = MyDb.OpenRecordset(dbOpenDynaset,"Publishers")
Set MyFd = MyDb("PubID")
Do While Not MyDn.EOF
Print MyFd
MyDn.MoveNext
Loop

Properties
Attributes CollatingOrder Name
OrdinalPosition Size SourceField
SourceTable Type Value

Methods
Append AppendChunk FieldSize
GetChunk

Visual Basic Book 8 © Mark Collins 1999 Page 16


Snapshot Object
A type of recordset that is the result of a query (similar to a Dynaset) but does not have
updatable records. Like a Table, a Snapshot has records and fields. A Snapshot is a static
picture of a set of records you can use to find data or generate reports. A Snapshot can contain
fields from one or more tables in a database.
In the Professional Edition, you can declare an object variable as a Snapshot type. To create a
Snapshot for an object variable, use the CreateSnapshot method on a Database, Dynaset, or
another Snapshot. You can have more than one Snapshot object variable containing the same
set of records.
Like all recordsets, when you create a Snapshot, the first record is the current record, and you
can use any of the Move methods, such as MoveNext, to move the current record to a
different record. You can also use the Find methods, such as FindFirst, to move to a specific
record. To cycle through all records, you can use the BOF and EOF properties to check for
the beginning or end of the Snapshot.

Properties
BOF Bookmark Bookmarkable
EOF Filter NoMatch
Sort

Methods
Clone Close CreateSnapshot
FindFirst FindLast FindPrevious
ListFields MoveFirst MoveLast
MoveNext MovePrevious

Visual Basic Book 8 © Mark Collins 1999 Page 17


Index Object
An object contained in the Indexes collections of Table and TableDef objects. Indexes are
used to order records by one or more key fields within a table. They speed up the process of
finding records, and can enforce unique values in each field named in the Index. An Index is
stored in the database as a retrievable object. A table can have none, one, or more indexes.
The Name property of an Index object is not the same as the name of an object variable to
which it is assigned. In the Professional Edition, you can declare an object variable as an
Index type.
A Table usually should have an index uniquely identifying each record, called a "primary
key" index. A primary key index is indicated with the Primary property of an Index object.
Although an Index can help find records quickly, if you are frequently updating a table with
several indexes, it can actually slow down the updating process. Creating a new Index on a
table with many existing records can be a very lengthy process. If there is no Index on a
Table, finding records can be a lengthy process also.

To create an index for a Table


1 Create a New Index object.
2 Set its properties.
3 Add it to the Indexes collection of a TableDef with the Append method.
The Seek method of a Table uses an index of the Table to find specific records.

Properties
Fields Name Primary
Unique

Methods
-

Visual Basic Book 8 © Mark Collins 1999 Page 18


Exercises
Preparation
Create directories in preparation for the following projects...
• Employee
• empPdox

Exercise 1
With this exercise you will create a simple database using the Data Manager for use in later
exercises.
1 Open the Visual Data Manager, select File / New / Access 7.0 and create
EMPLOYEE.MDB in the C:\Temp directory.

2 Right mouse click on the Database Window and then click the New Table to create a
new table ( call it DEPT ). Then select the Add Field button in the Fields section to
add the fields shown below...

Field Name Field Type Field Size


Dept Name Text 25
Dept Code Text 4

Then click the Close button when finished.


3 Then add an Index as follows...

Index Name Indexed Fields


deptndx Dept Code

making sure that the ‘Unique Index Value’ and the ‘Primary Index’ check boxes are checked.
Once that’s done click Build Table.

4 Close that table design window and create a second table called EMPLOYEE. Create
the following fields and index...
Field Name Field Type Field Size
Emp Code Integer 2
Emp Name Text 25
Salary Currency 8
Dept Text 4
Date of Birth Date/Time 8

Visual Basic Book 8 © Mark Collins 1999 Page 19


Index Name Indexed Fields
empndx Emp Code

5 Return to the Database Window, double click on the Dept table. Obviously there is
no data yet so click on Add to create some. Click Update and then Add after each
record to create the next until the last record when you should click Close. Enter the
following records...

Dept Code Dept Name


MKTG Marketing and Sales
ACCS Accounts
ADMN Administration

Now add some records to the Employee table.


Emp Code Emp Name Salary Dept Date of Birth
1001 Adam Berry 17500 ACCS 12/03/64
1023 Caroline Dewey 24000 MKTG 25/07/58
2062 Edwina Franks 21000 ADMN 17/12/62

6 Close the Visual Data Manager.

Visual Basic Book 8 © Mark Collins 1999 Page 20


Exercise 2
This exercise creates several forms for manipulating and viewing the data stored in the
Employee database created in exercise 1
1 Start a new project. On the default existing form place a Data control, two TextBoxes
and two labels. Set their properties as From 1 below...
Object Property Value (Form1) Value (Form2)
Form Name frmDept frmEmp
Caption Department Table Employee Table
Data Control Name dtaDept dtaEmp
DatabaseName ...\EMPLOYEE.MDB ...\EMPLOYEE.MDB
RecordSource Dept Employee
Label #1 Caption Department Code: Employee Code:
Label #2 Caption Department Name: Employee Name:
Label #3 Caption n/a Salary:
Label #4 Caption n/a Department:
Label #5 Caption n/a Date of Birth:
TextBox #1 Name txtCode txtCode
DataSource dtaDept dtaEmp
DataField Dept Code Emp Code
TextBox #2 Name txtName txtName
DataSource dtaDept dtaEmp
DataField Dept Name Emp Name
TextBox #3 Name n/a txtSal
DataSource n/a dtaEmp
DataField n/a Salary
TextBox #4 Name n/a txtDept
DataSource n/a dtaEmp
DataField n/a Dept
TextBox #5 Name n/a txtDOB
DataSource n/a dtaEmp
DataField n/a Date of Birth

Visual Basic Book 8 © Mark Collins 1999 Page 21


2 Test Run your form, see how already you have gained access to the database. Change
the name of the Accounts department to “Accounts & Finance” using the text box.
3 Create a second form called frmEmp to access the employee table. Create it as the first
one but with five text boxes and labels and set the properties as Form 2 from the table
above.
4 Finally Create a third form. This one isn’t that simple as we want to view data from a
Dynaset created by an SQL query. Set the following properties...
Object Property Value
Form Name frmJoin
Caption Dynaset Join
Data Control Name dtaJoin
DatabaseName ...\EMPLOYEE.MDB
RecordSource blank
TextBox #1 Name txtEmpName
DataSource dtaJoin
DataField blank
TextBox #2 Name txtDeptName
DataSource dtaJoin
DataField blank
Label #1 Caption Employee
Label #2 Caption Department

5 Now for some code. Firstly place two lines in the Load event procedure of the
Department form to show the other forms...
Sub Form_Load ()
frmEmp.Show
frmJoin.Show
End Sub

Visual Basic Book 8 © Mark Collins 1999 Page 22


Next we need some code in the Join form to set up a record set based upon an SQL
query performing a join. NB that the SQL statement has to typed as the example
below otherwise the SQL string will not be correctly interpreted by VB. We also need
to bind the controls on the form...

Sub Form_Load ()
' create SQL query string
Dim QSQL As String
QSQL = "SELECT [Emp Name], [Dept Name] FROM Employee, Dept "
QSQL = QSQL & "WHERE Employee.Dept = Dept.[Dept Code];"

' setup dynaset as record source


dtaJoin.RecordSource = QSQL

' Bind controls


txtEmpName.DataField = "Emp Name"
txtDeptName.DataField = "Dept Name"

' Refresh all connections


dtaJoin.Refresh
End Sub

6 Save all the forms and the project file in the Employees directory. Run your
application...
7 See how we have two forms viewing data from a table each, and a third form viewing
data from both. Try changing things about...
• Give someone a middle initial in their name, does this change reflect elsewhere?
• If you change someone’s department in the Employee form why isn’t the change
reflected in the join.
The next booklet continues with this subject, and the exercises there will extend this project.

Visual Basic Book 8 © Mark Collins 1999 Page 23

You might also like