visual basic 5-6 course part 9

27
Visual Basic 5 Programming - 9 A Specialised Training Course

Upload: mark-collins

Post on 10-Apr-2015

152 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Visual Basic 5-6 Course Part 9

Visual Basic 5 Programming - 9

A Specialised Training Course

Page 2: Visual Basic 5-6 Course Part 9

Visual Basic Book 9 © Mark Collins 1999 Page 1

Contents

PROGRAMMING WITH DATA ACCESS OBJECTS............................................................................. 2

DATA DEFINITION LANGUAGE (DDL) ................................................................................................. 3

MANIPULATING THE DATABASE OBJECT ........................................................................................ 3

OPENING A DATABASE .............................................................................................................................. 3

OpenDatabase Function ................................................................................................................... 3

EXAMPLES: ............................................................................................................................................... 4

CLOSING DATABASES................................................................................................................................ 4

Close Method .................................................................................................................................... 4

CREATING A DATABASE ............................................................................................................................ 5

CreateDatabase Function ................................................................................................................. 5

MANIPULATING DATABASE STRUCTURE ......................................................................................... 6

ADDING AND DELETING TABLES FROM A DATABASE ................................................................................ 6

TableDef.Append Method ................................................................................................................. 6

TableDefs.Delete Method.................................................................................................................. 6

AMENDING A TABLES STRUCTURE ............................................................................................................ 7

Fields.Append Method ...................................................................................................................... 7

Deleting or changing a Field ............................................................................................................ 7

Indexes.Append Method .................................................................................................................... 8

Indexes.Delete Method...................................................................................................................... 8

USING TABLES, DYNASETS AND SNAPSHOTS................................................................................... 9

RECORDSETS REVISITED ............................................................................................................................ 9

CREATING A TABLE VARIABLE................................................................................................................ 10

OpenTable Method.......................................................................................................................... 10

CREATING A DYNASET............................................................................................................................ 11

CreateDynaset Method.................................................................................................................... 11

CREATING A SNAPSHOT........................................................................................................................... 13

CreateSnapshot Method .................................................................................................................. 13

SORTING RECORDSETS ............................................................................................................................ 13

Ordering Tables .............................................................................................................................. 13

Ordering Dynasets and Snapshots .................................................................................................. 14

Selecting a subset of Records .......................................................................................................... 14

MOVING ABOUT A RECORDSET................................................................................................................ 15

The Move methods........................................................................................................................... 15

The Find Methods ........................................................................................................................... 16

The Seek Method ............................................................................................................................. 17

Using Bookmarks ............................................................................................................................ 17

ADDRESSING OBJECTS ............................................................................................................................ 18

CHANGING THE DATA.............................................................................................................................. 19

Presenting Data .............................................................................................................................. 19

Presenting Field Values .................................................................................................................. 20

Amending and Appending Records ................................................................................................. 20

Edit Method..................................................................................................................................... 21

AddNew Method .............................................................................................................................. 21

Update Method................................................................................................................................ 21

APPENDIX .................................................................................................................................................. 22

A. FIELD TYPE AND SIZE PROPERTIES ..................................................................................................... 22

B. COMMON RECORDSET PROPERTIES .................................................................................................... 23

EXERCISES ................................................................................................................................................ 24

Page 3: Visual Basic 5-6 Course Part 9

Visual Basic Book 9 © Mark Collins 1999 Page 2

Programming with Data Access Objects In the previous booklet we saw how to use the Data Control to link database files and

tables with other bound controls. It transpired that the Data Control contains Objects

that, through a hierarchical structure, allow us to logically represent actual database,

tables, fields etc. and by using the Professional Edition we can also create object variables

of these types. The Data Control by itself is fairly limited, the real power comes from

manipulating the objects.

The following diagram illustrates the links between objects. ‘Sharp’ boxes represent

Record Sets objects, Ovals represent collections of objects and ‘soft’ boxes represent

other objects...

Database

Table QueryDef TableDefs

SnapshotDynaset

Indexes

Index

Fields

Field

TableDef

Fields Indexes

Field Index

Reading, Editing, Adding

& Deleting Data

Mapping, Creating,

Editing & Deleting

Structure

Data Data Definition

Definition

Definition

Definition

Collections:

A reminder about collections (shown as ovals in the above diagram); They are an ordered

set of objects of a similar type. The are referenced like an array from zero to one less

than the count of objects. As changes occur to the collection the position of a particular

object is likely to change.

Page 4: Visual Basic 5-6 Course Part 9

Visual Basic Book 9 © Mark Collins 1999 Page 3

Data Definition Language (DDL) The code you use in Data Access projects will involve a combination of...

• Object Methods

• Independent Statements & Functions

For example, to open a Database using object variables you would use the OpenDatabase

Function whose return value is of type Database...

Set dbAlpha = OpenDatabase( filename )

To then subsequently open a table, assigning it to a Table object you would use the

OpenTable method of a database object...

Set tbBeta = dbAlpha.OpenTable( tableName )

The easiest way to investigate this is to look at typical tasks to perform and examine the

methods, functions and statements involved.

Manipulating the Database Object

Opening a Database

Sequence...

• Create a Database Object Variable

• Use the OpenDatabase function

OpenDatabase Function

Syntax...

Set dbvar = OpenDatabase( dbName [,excl [,readonly

[,connect]]])

The function returns a Database Object.

Argument Description

dbName the path of the database to open. If Access or Btrieve then it

is a filename; for Paradox, Foxbase and dBase it is a

directory name. See next table for more details

excl If True, the database opens for exclusive (single-user) access

and if False, the database opens for multiuser access. The

default is False

readonly

If True, the database opens for read-only access and if False,

the database opens for read/write access. The default is

False.

connect A string expression used for opening the database.

Page 5: Visual Basic 5-6 Course Part 9

Visual Basic Book 9 © Mark Collins 1999 Page 4

Possible settings for the supported database formats are:

Database format DatabaseName Connect

Microsoft Access drive:\path\filename (none)

dBASE III drive:\path dBASE III;

dBASE IV drive:\path dBASE IV;

dBASE 5 drive:\path dBASE 5.0;

Paradox 3.x drive:\path Paradox 3.x;

Paradox 4.x drive:\path Paradox 4.x;

Paradox 5.x drive:\path Paradox 5.x;

FoxPro 2.0 drive:\path FoxPro 2.0;

FoxPro 2.5 drive:\path FoxPro 2.5;

FoxPro 2.6 drive:\path FoxPro 2.6;

Examples: Set dbAlpha = OpenDatabase( “C:\Access\Alpha\Alpha.MDB”, True)

Set dbBeta = OpenDatabase(“C:\Beta”,False,False,“Paradox III;”)

Closing Databases

Once you have finished with a database you should close it. This releases the resources

that it holds as well as any locks. You must close all recordsets opened within it first.

Close Method

Closes the object to whom the method belongs. To close a database use the following

syntax...

dbAlpha.Close

Page 6: Visual Basic 5-6 Course Part 9

Visual Basic Book 9 © Mark Collins 1999 Page 5

Creating a Database

It is possible to create a database from within a project using the CreateDatabase

function.

CreateDatabase Function

Creates a Microsoft Access database, and returns a Database object that is open for

exclusive read/write access using the following syntax...

Set dbvar = CreateDatabase( dbname [, locale [, options ]] )

Argument Description

dbname A string expression for the name of your new database. It can be a fully

qualified path, such as C:\MYDB.MDB.

locale A string expression specifying the language information for creating the

database. This parameter is required, incorrect or nonexistent

information in this part will cause a run time error. The default value

and valid setting for the UK is dbLangGeneral.

options A Long numeric value indicating one or more options. See the table,

below. You can indicate more than one option by adding values

together.

The values or symbolic constants for the options argument are...

Constant Definition

dbEncrypt Encrypt the database. To decrypt a database, use the

CompactDatabase statement.

dbVersion10 Creates a database that uses the Microsoft Jet database

engine version 1.0 file format.

dbVersion11 Creates a database that uses the Microsoft Jet database

engine version 1.1 file format.

dbVersion20 Creates a database that uses the Microsoft Jet database

engine version 2.0 file format.

dbVersion30 (Default) Creates a database that uses the Microsoft Jet

database engine version 3.0 file format (compatible

with version 3.5).

The CreateDatabase function opens the new database for exclusive access. To open it for

multiuser access you can use the Close method on the database, then open it again with

the OpenDatabase function.

Page 7: Visual Basic 5-6 Course Part 9

Visual Basic Book 9 © Mark Collins 1999 Page 6

Manipulating Database Structure In the diagram at the start of the book you will see that, below the Database Object, the

objects are split into two groups...

• those used for manipulating data and

• those used for manipulating structure.

We will look at the second group first.

Adding and Deleting Tables from a Database

One of the properties of a Database object is the Tabledefs Collection. This maintains a

description of each table in that Database. A TableDef object is a single member of that

collection. To manipulate existing tables we can use the object’s methods, but to

maintain the collection we use the collection’s methods. As we will see later these

methods are common to other collections.

TableDef.Append Method

Adds a new TableDef object to the collection.

TableDefsObj.Append newTableDef

You must set the property values of the new TableDef before you append the object to the

collection. Once the TableDef is appended to a collection, its property values become

read-only. For example...

Dim dbX As Database

Dim fdA As New Field

Dim tdfB As New TableDef

fdA.Name = “Dept Code”

fdA.Type = dbText

fdA.Size = 4

tdfB.Fields.Append fdA ‘ append for fields collection

... ‘ add other fields etc...

tdfB.Name = “Dept”

Set dbX = OpenDatabase(“C:\Employee\Employee.MDB”)

dbX.TableDefs.Append tdfB

TableDefs.Delete Method

Removes a TableDef from the collection.

Dim dbX As Database

...

dbX.TableDefs.Delete “Dept”

Page 8: Visual Basic 5-6 Course Part 9

Visual Basic Book 9 © Mark Collins 1999 Page 7

Amending a Tables structure

As already mentioned, the structure of a table is contained in a TableDef object. We have

just seen how to add and delete a TableDef in a database but noted that the TableDef must

be defined fully before adding, as all the properties become Read-Only. The example

showed us adding (appending) fields to the TableDef, we must also define the Indexes

and other properties. We are familiar with setting ordinary properties, but the TableDef

has two properties that are collections...

• Fields

• Indexes

Firstly we shall concentrate on fields...

Fields.Append Method

Adds a Field object to a Fields collection and therefore a TableDef. As with the

TableDefs Append method most properties of the Field Object must be set before

appending, all but the Value property. Obviously that can change later.

For example...

Dim fdA As New Field

Dim tdfB As TableDef

fdA.Name = “Dept Code”

fdA.Type = dbText

fdA.Size = 4 ‘ only necessary for String data

tdfB.Fields.Append fdA ‘ append for fields collection

For a list of possible Type Property values and associated sizes see the appendix. The

Name property of a field object determines the fields name and must be unique within a

single TableDef. The Attributes property of a field determines how that field behaves

(updatable, Counter field or of Fixed Size). SourceTable and SourceField properties are

Read-Only and indicate the physical table and field of a logical field object.

Deleting or changing a Field

It is not possible to simply delete a Field from a collection or amend the definition

properties of a Field. To change a table in this way you need to create a new table that

includes the changes. As you can imagine this can cause problems with the data contained

in a table and shows how valuable it is to design your database correctly from the start.

Page 9: Visual Basic 5-6 Course Part 9

Visual Basic Book 9 © Mark Collins 1999 Page 8

Indexes.Append Method

An individual Index object can also be included in a Table by appending it to the Indexes

collection of a TableDef. It too needs to have all its properties set before being

appended...

Dim tdfB As TableDef

Dim idxC As New Index

idxC.Name = “DeptCodeIndex”

idxC.Fields = “Dept Code”

idxC.Unique = True

idxC.Primary = True

tdfB.Indexes.Append idxC

Indexes.Delete Method

Unlike a Field Object, an Index Object can be deleted from a collection and therefore a

TableDef.

tdfB.Indexes.Delete “DeptCodeIndex”

Page 10: Visual Basic 5-6 Course Part 9

Visual Basic Book 9 © Mark Collins 1999 Page 9

Using Tables, Dynasets and Snapshots

Recordsets revisited

In order to manipulate data it is best to use a Recordset. Recordset is the term to describe

the following group of objects...

• Table

• Dynaset

• Snapshot

These objects can all be found on the left hand side of the object hierarchy diagram at the

beginning of this booklet. You may prefer to think of them as Views.

A recordset has a two dimensional structure, containing records (rows) and fields

(columns). Whereas a Table is probably a normalised set of records forming part of your

database a Dynaset or Snapshot can combine data from several tables.

Tables as opposed to Tables...

Although not absolutely necessary, it is useful to distinguish between a physical “base

table” (the actual part of the actual database that stores the data) and a table object that

refers to a base table. Remember it is possible for several Table Objects to refer to the

same base table.

These objects have various differences...

• Dynasets and Snapshots are the results of Queries. A Table is not.

• Once a Dynaset or Snapshot is created it does not automatically change to reflect the

additions and deletions of records by other users. A Table will.

• A Dynaset or Table will reflect any changes to the data in existing records from other

sources.

• A Snapshot does not allow you to change the underlying data at all.

• When you only want to read data and not change data, a Snapshot is faster than a

read-only Dynaset. However, a read-only Dynaset will reflect changes made by

others while you are using it; a Snapshot will not.

The Recordsets share similar properties, these are described in Appendix B.

Page 11: Visual Basic 5-6 Course Part 9

Visual Basic Book 9 © Mark Collins 1999 Page 10

Creating a Table Variable

By creating a table variable and setting it to refer to an existing table you can then

manipulate the data contained in that table. To do this you need...

OpenTable Method

This is a Database Object Method. Opens a Table and returns a Table Object

Dim dbA As Database

Dim tblB As Table

Set dbA = OpenDatabase(“C:\Employee\Employee.MDB”)

Set tblB = dbA.OpenTable(“Dept”)

It is also possible to add numeric expression indicating one or more option settings after

the table name. Values can be combined by adding them together and are described in

the following table...

Constant Value Description

dbDenyWrite 1 In a multiuser or multitasking environment, others cannot

make changes to any records in the Table while you have it

open. Use for administrative purposes only.

dbDenyRead 2 In a multiuser or multitasking environment, others cannot

read any records in the Table while you have it open. Use

for administrative purposes only.

dbReadOnly 4 You cannot make changes to records in the Table. This can

increase the speed of some operations.

Page 12: Visual Basic 5-6 Course Part 9

Visual Basic Book 9 © Mark Collins 1999 Page 11

Creating a DynaSet

There are several ways to create a Dynaset but each use the following method...

CreateDynaset Method

This is a method of a Database, QueryDef , Table, Snapshot or even another Dynaset

Object. It creates and returns a Dynaset Object and uses the following alternative

syntaxes...

Set dynasetObj = dbObj.OpenRecordset( source [,options] )

Set dynasetObj = {recordset|querydef}.OpenRecordset(options)

The source can be any valid...

• Table name

• QueryDef Object name

• SQL query string

The options argument is a numeric expression indicating one or more option settings.

Values can be combined by adding them together. See the following table for option

values...

Constant Value Description

dbDenyWrite 1 In a multiuser or multitasking environment, others

cannot make changes to any records in any table in your

Dynaset while you have it open.

dbReadOnly 4 You cannot make changes to records in your Dynaset.

dbAppendOnly 8 You can only add new records to the Dynaset.

dbInconsistent 16 Updates can apply to all fields of the Dynaset, even if

they also affect other rows of the Dynaset.

dbConsistent 32 (Default) Updates apply only to those fields that will

not affect other rows of the Dynaset.

dbSQLPassThrough 64 For Dynasets created with an SQL statement, this value

causes the SQL statement to be passed to an ODBC

database for processing.

Page 13: Visual Basic 5-6 Course Part 9

Visual Basic Book 9 © Mark Collins 1999 Page 12

Some examples will explain the possibilities, assume the following in each case...

Dim dynX As Recordset, dynY As Recordset

Dim dbA As Database

Dim tblB As Table

Dim qdfC As QueryDef

Dim SQLQ As String

Set dbA = OpenDatabase(“C:\Employee\Employee.MDB”)

Set tblB = dbA.OpenTable(“Dept”)

‘ There is an existing QueryDef called “JoinDeptEmp”

Set qdfC = dbA.OpenQueryDef(“JoinDeptEmp”)

SQLQ = “SELECT [Dept Name], [Employee Name] ”

SQLQ = SQLQ & “FROM Dept, Employee ”

SQLQ = SQLQ & “WHERE Dept.[Dept Code] = Employee.Dept;”

Firstly two ways to create a Dynaset based upon a table without any options...

Set dynX = dbA. OpenRecordset(“Dept”)

Set dynX = tblB. OpenRecordset()

Next to create a Dynaset from a QueryDef...

Set dynX = dbA. OpenRecordset(“JoinDeptEmp”)

Set dynX = qdfC. OpenRecordset()

We can simply use an SQL string to define the Dynaset...

Set dynX = dbA. OpenRecordset(SQLQ)

To create a Dynaset based upon another Dynaset...

Set dynY = dynX. OpenRecordset()

Although there is an alternative method that is more efficient...

Set dynY = dynX.Clone()

Page 14: Visual Basic 5-6 Course Part 9

Visual Basic Book 9 © Mark Collins 1999 Page 13

Creating a Snapshot

This is similar to creating a Dynaset except we use a different method...

CreateSnapshot Method

The syntax is either...

Set snapshot = OpenDatabase.RecordSet( source [, options ] )

Set snapshot = database.OpenRecordset(options)

As a snapshot is more limited than a Dynaset the options available are fewer...

Constant Value Description

dbDenyWrite 1 In a multiuser environment, others cannot make

changes to records in any table in your Snapshot while

you have it open. Use for administrative purposes

only.

dbSQLPassThrough 64 For Snapshots created with an SQL statement, this

value causes the SQL statement to be passed to an

ODBC database for processing.

Sorting Recordsets

Depending on the circumstances you may need to present the records in a Recordset in a

specific order. The possibilities depend on the Recordset.

Ordering Tables

The default order of a set of records (if that isn’t a contradiction) in a table is the order in

which they were added.

Indexes however allow you to determine the order. To do so you set the Index Property

of a table to a valid, defined index for that table...

...

Dim tblA As Table

Set tblA = db.OpenTable(“Dept”)

tblA.Index = “DeptCodeIndex”

...

To view your records in an order not defined in an index you would need to either create a

new index or create a Dynaset specifying the order.

Page 15: Visual Basic 5-6 Course Part 9

Visual Basic Book 9 © Mark Collins 1999 Page 14

Ordering Dynasets and Snapshots

For simplicity I will refer to Dynasets, but unless I specifically state otherwise I mean

Snapshots too.

If a Dynaset is opened on a table without any specific order the records are sorted on the

Primary Index. If no Primary Index exists they are ordered in the tables default order.

You can specify which specific Index to use however using the Order By clause of a

query...

...

Dim dynX As Recordset

qryY = “SELECT * FROM Employee ORDER BY Salary”

Set dynX = db. OpenRecordset(qryY)

...

When you create a Dynaset from a Dynaset you can use the Sort Property.

The Sort Property of a Dynaset determines the order of records subsequently created

from the recordset with CreateDynaset or CreateSnapshot.. It is effectively the ORDER

BY clause in an SQL statement.

You create a Dynaset, set its Sort property, and then create a new Dynaset or Snapshot.

If you create a Dynaset using an SQL statement, there is no need to set this property. The

Sort property of the new recordset is empty.

The default sort order is ascending. The following examples show how you can set the

sort order to ascending and descending and how to include several levels of sorting...

dynA.Sort = "[Employee Name]" ' Ascending order.

dynA.Sort = "[Dept] Asc,[Employee Name] Desc"

dynA.Sort = "[Employee Name] Desc"

Selecting a subset of Records

Remember that a Table Object is a logical representation of a physical Base Table and

therefore contains all records at all times. The Find Methods (see later) allow you to

select which records to view in a table.

If we want a complete Recordset that is a ‘subset’ of another Recordset we need Dynasets

and Snapshots. There are two ways of performing this...

• Place a condition in a query

• Place a condition in the Filter property of a Dynaset or Snapshot Source

The syntax of the condition is simply...

field operator value

for example...

[Dept Name] = ‘Accounts’ [Salary] > 20000

[Employee Name] LIKE ‘*Smith*’

Page 16: Visual Basic 5-6 Course Part 9

Visual Basic Book 9 © Mark Collins 1999 Page 15

A condition is either placed in a Query such as...

...

Dim dynX As Recordset

qryY = “SELECT * FROM Employee Where Salary > 20000”

Set dynX = db.RecordSource = qryY

...

Or a new Dynaset is created from an existing Dynaset with the filter property set...

...

Dim dynX As Recordset, dynY As Recordset

Set dynX = db.OpenRecordset(“Employee”, dbOpenDynaset)

dynX.Filter = “[Salary] > 20000 AND [Dept] = ‘ACCS’”

...

Moving about a Recordset

To change the current record in code there are methods (common to all Recordsets)

categorised as the...

• Move Methods ‘group’

• Find Methods ‘group’

• Seek Method

There is also a feature known as BookMarks that you can use...

The Move methods.

• MoveFirst

• MoveLast

• MoveNext

• MovePrevious

For those of you who like to think of pointers these methods change the Record Pointer.

The extreme moves (MoveFirst & MoveLast) can be used easily. With the incremental

moves (MoveNext & MovePrevious) errors can occur if you attempt to move to a record

before the first record or after the last record. So in a loop you might consider...

For I = 0 to dynA.RecordCount - 1

‘Do something

dynA.MoveNext

Next

However the RecordCount property can not be depended on to be accurate (especially

with transactions) so it is preferable to use the EOF or BOF properties...

Do Until dynA.EOF

‘Do Something

dynA.MoveNext

Loop

When you open the recordset, the first record is current and the BOF property is False. If

recordset contains no records, both BOF and EOF properties are True, and there is no

current record.

These four methods relate to the four buttons on the Data Control.

Page 17: Visual Basic 5-6 Course Part 9

Visual Basic Book 9 © Mark Collins 1999 Page 16

The Find Methods

• FindFirst

• FindLast

• FindNext

• FindPrevious

These methods locate the first, last, next, or previous record that satisfies a specified

criteria and make that record the current record.

recordset.FindFirst criteria

recordset.FindLast criteria

recordset.FindNext criteria

recordset.FindPrevious criteria

The criteria is a string expression equivalent to the WHERE clause in an SQL string

specifying the records you want.

If the recordset contains more than one record that matches criteria, FindFirst locates the

first occurrence, FindNext locates the next occurrence, and so on.

You can follow a Find operation with a Move operation, such as MoveNext, which moves

to the next record regardless of whether it matches any criteria.

If no matching records are found, the NoMatch property is True and the current record

remains the same as before the Find method was used.

e.g.

Dim dynA As Recordset, Criteria As String

Criteria = “ Dept = ‘ACCS’ ”

...

dynA.FindFirst Criteria' Find first matching record.

...

If Not dynA.NoMatch Then ' if record is found.

dynA.FindNext Criteria ' Find next matching record.

...

Page 18: Visual Basic 5-6 Course Part 9

Visual Basic Book 9 © Mark Collins 1999 Page 17

The Seek Method

When you have an Indexed Table Object Variable the Seek method is the most efficient

way to find a record. It locates a record in an indexed table that meets the specified

criteria for the current index and makes it the current record.

table.Seek comparison, key1, key2...

The comparison indicates the kind of comparison that will be performed and is one of the

following string expressions: <, <=, =, >=, >, or <>.

The other arguments, key1, key2 etc. are the values for each field in the table's current

index to be compared against.

You must set the current index with the Index property before you use Seek. If the index

identifies a non-unique key field, Seek locates the first record satisfying the criteria. The

value of each key value must be of the same data type as the corresponding field in the

current index.

When the comparison is =, >=, >, or <>, Seek starts at the beginning of the index and

searches forward. When the comparison is <= or <, Seek starts at the end of the index

and searches backward.

After the seek you should check the value of the NoMatch property to determine whether

the Seek method has succeeded. If it fails, NoMatch is True and the current record is

unchanged.

For example...

Dim tblA As Table

Set tblA = db.OpenTable("Employee")' Open a table.

tblA.Index = "by Salary" ' Define current index.

tblA.Seek ">=", 20000 ' Salary greater than 20k

If MyTable.NoMatch Then... ' perform check

Using Bookmarks

A recordset has a Bookmark property that determines which record in a recordset is the

current record.

When a recordset is created or opened, each record already has a unique bookmark. You

can save the bookmark for the current record by assigning the value of the Bookmark

property to a variable (string or variant). To quickly return to that record at any time after

moving to a different record, set the recordset's Bookmark property to the value of that

variable. The value of the Bookmark property is not however the same as a record

number.

To make sure the recordset supports bookmarks, inspect the value of the Bookmarkable

property. If Bookmarkable is False, the recordset doesn't support bookmarks.

Dim Place As Variant

If dynA.Bookmarkable = True Then

Place = dynA.Bookmark ‘Remember position

... ‘Do something

If dynA.Bookmarkable = True Then

dynA.Bookmark = Place ‘Reset position

Page 19: Visual Basic 5-6 Course Part 9

Visual Basic Book 9 © Mark Collins 1999 Page 18

Addressing Objects

So far we have looked at the upper levels of our object diagram. As we prepare to

manipulate individual field object data it is worth clarifying the various ways of referring

to objects.

If each object has a variable this is simple, we can refer to an individual property or

method of an object from there...

Dim dbA As Database, tblB As Table

Dim dynC As Recordset, fdD As Field

Set dbA = OpenDatabase(...)

Set tblB = dbA.OpenTable(“Employee”)

Set dynC = tblB. OpenRecordset()

Set fdD = dynC.Fields.(“Salary”)

fdD.Value = 25000

The problem with this is when we come to manipulate Databases with a large number of

Tables, Dynasets and Fields etc. This would require lengthy Dim statements and a

multitude of variable names to remember. A better way is to string objects together...

dbA.TableDefs(“Dept”).Fields(“Dept Name”).Size = 20

dynC.Fields(“Salary”).Value = 25000

dynC.Fields(“Dept”).Value = “ACCS”

This can be shortened by use of the Default collections and properties...

Object Default Collection Default Property

Database TableDefs Connect

Field Value

Index Name

QueryDef Name

Recordset Fields Name

TableDefs Fields Name

You can also use the name of a default directly or the ordinal number of an object in a

collection, for example these five lines are refer to the same table (assuming Dept is the

first table)...

dbA.TableDefs(“Dept”)

dbA.TableDefs(0) dbA(“Dept”) dbA(0) dbA!Dept

Page 20: Visual Basic 5-6 Course Part 9

Visual Basic Book 9 © Mark Collins 1999 Page 19

We have even more possibilities when referring to the value of a field in a dynaset using

defaults...

txtCode = dynC.Fields(“Employee Code”).Value

txtCode = dynC.Fields(“Employee Code”)

txtCode = dynC(“Employee Code”) txtCode = dynC![Employee Code]

txtCode = dynC.Fields(0).Value

txtCode = dynC.Fields(0)

txtCode = dynC(0)

As you can begin to see, we need relatively few object variables to access all the objects

in a Database. If in doubt use a longer reference, recognising the defaults when writing the

code will become habit, don’t feel you must use them immediately.

Changing the Data

Once you have set the necessary upper level objects (Database, Tables and Dynasets) you

can now begin to access the data.

Presenting Data

We have seen how to move between records in a recordset by changing the current record.

We have also seen various ways to reference field values in a recordset. This is all well

and good, but so far we have not looked at presenting that data on screen.

With the Data Control you could create Bound Controls that automatically changed to

reflect the value of a field in the current record. Without a Data Control this needs to be

done manually. You therefore need controls to...

• Change the current record

• Display the data

Although why restrict yourself to a single record. We are no longer restricted in the

controls we can use, so why not present a whole Table in a Grid Control? An exercise

later on shows you how to do this. Other options for displaying data include...

• A Text Box for a numeric or textual field

• A Label for a numeric or textual field

• A Check box for a boolean field

• A Gauge for numeric data

• Combo Box with possible values to choose from

• Option buttons for limited choice

If displaying a single record you will need a control to change the current record, the

possibilities include...

• Command Buttons suitable labelled

• A Scroll Bar (vertical or horizontal)

• Menu options

• The Spin Control

• A List or Combo Box

• A Text box representing a field used in a Seek or Find method

As you can see, the possibilities are endless, especially as third-party controls become

available.

Page 21: Visual Basic 5-6 Course Part 9

Visual Basic Book 9 © Mark Collins 1999 Page 20

Presenting Field Values

Once you have selected your control to display a field you need code to assign the values.

Depending on your record selection method there are several possible events to consider.

Whichever event you choose you simply require a line such as...

txtCode = dynC![Employee Code]

to transfer the Employee Code field value to a TextBox. Or for a Boolean Field shown

using a Check Box...

chkAlive = NOT dynX![Dead]

Amending and Appending Records

When you want to edit a field you need to perform the following...

• Use the Edit Method on the record

• Change the field(s) value

• Use the Update Method on the record

There may be circumstances where you wish to change field values using code, such as

giving everyone a ten percent pay rise...

...

tblEmp.MoveFirst

Do Until tblEmployee.EOF

tblEmp.Edit

tblEmp!Salary = tblEmp!Salary * 1.1

tblEmp.Update

tblEmp.MoveNext

Loop

...

More commonly you will allow your user to change values in a control representing a

field and reflect that change in the underlying data. For this it is best to use Edit and

Update buttons. Alternatively whenever you move to a new record you could use the

Update Method on the last record, and use the Edit Method on the new record.

To add a new record you...

• Use the AddNew Method

• Set the field values

• Use the Update Method

You could add another button captioned New or Add or design your code so that moving

beyond the last record automatically calls a procedure that invokes the AddNew Method.

Alternatively you can use Action Queries that actually perform changes. They are

effectively SQL statements and bypass the need for the above methods. Instead they use

the following methods...

• ExecuteSQL Method

• Execute Method

Page 22: Visual Basic 5-6 Course Part 9

Visual Basic Book 9 © Mark Collins 1999 Page 21

Edit Method recordset.Edit

Use the Edit method to allow changes to the current record and to lock the current record

to prevent changes by other users. Using Edit a second time without using Update will

undo any changes made to the record in the copy buffer.

Using Edit will produce an error in the following conditions:

• There is no current record.

• The database or recordset is read-only.

• No fields in the record are updatable.

• The database or recordset was opened for exclusive use by another user.

AddNew Method recordset.AddNew

The AddNew method sets all fields in the copy buffer to Null and makes it the current

record.

The new record's apparent position in the recordset depends on whether you add new

records to a Table or a Dynaset. If you add a new record to a Table, the new record

appears in its position in the table according to the current index. If you add a new record

to a Dynaset, the new record appears at the end of the Dynaset.

When you use the Update method after AddNew, the record that was current before you

executed AddNew becomes the current record again, and the new record is added to the

recordset. To make the new record current after you use Update either...

• Set the Bookmark equal to the LastModified property.

• Use MoveLast with a Dynaset or a Table that does not have an index.

• Use Seek with a Table that has an index.

Update Method recordset.Update

Use Update to save any changes to a record after using Edit or AddNew.

Caution If you are not using a data control and move to another record or close the

recordset while an Edit or AddNew operation is pending, any existing changes will be

lost and no error will occur.

Page 23: Visual Basic 5-6 Course Part 9

Visual Basic Book 9 © Mark Collins 1999 Page 22

Appendix

A. Field Type and Size Properties

The symbolic constants and settings of the Type property are:

Type Constant Value Size Description Visual Basic data type

dbBoolean 1 1 True/False Integer (0 or 1)

dbByte 2 1 Byte Integer (0 255)

dbInteger 3 2 Integer Integer

dbLong 4 4 Long Long

dbCurrency 5 8 Currency Double

dbSingle 6 4 Single Single

dbDouble 7 8 Double Double

dbDate 8 8 Date/Time Variant

dbText 10 var Text String

dbLongBinary 11 0 Long Binary String

dbMemo 12 0 Memo String

The Size property need only be set for the dbText, String type; other types are of constant

size.

Page 24: Visual Basic 5-6 Course Part 9

Visual Basic Book 9 © Mark Collins 1999 Page 23

B. Common Recordset Properties

Property Description

Connect Same as a Data Control

DateCreated & LastUpdated The dates the underlying table was created or modified last.

LockEdits Affects the locking behaviour of the Edit method

Name The value of the source of the recordset

SourceTableName for attached tables

Transactions Indicates whether transaction processing is supported

Updatable Indicates whether updates allowed

Filter A condition that may be applied to a recordset derived from

this one (not Tables)

Index The current Index Name (Tables Only)

Sort The ordering condition that can be applied

BOF True if the current record pointer is before the first record

(i.e. invalid)

EOF True if the current record pointer is after the last record (i.e.

invalid)

Bookmark The bookmark of the current record in the recordset. Can be

set to move to another record with the same value.

Bookmarkable Supports bookmarks or not

LastModified The bookmark of the last record that was inserted or altered

NoMatch Used with Seek or Find Methods

RecordCount The number of processed records in a recordset. Is not

always correct!

Page 25: Visual Basic 5-6 Course Part 9

Visual Basic Book 9 © Mark Collins 1999 Page 24

Exercises

Preparation

For the following exercises you will need...

• The Employee project from last week

• A project directory called DataGrid

Exercise 1

In this exercise we will add extra functionality to the Employee project from last week.

The project consists of three forms, two directly linked to tables and one to both tables via

a Dynaset. We shall now add some buttons (or menus if you prefer) to allow us to Add

records to our tables.

1 Add two command buttons to the Department Table Form. These should be captioned

Add and Update. Name them cmdAdd and cmdUpdate.

Give each the following code...

Sub cmdAdd_Click ()

dtaDept.Recordset.AddNew

End Sub

Sub cmdUpdate_Click ()

dtaDept.Recordset.Update

End Sub

2 Save and run your project again. Can you now add records?

3 As we are using a Data Control there is little error processing needed. You should

however modify the form so that...

• When the form is loaded the Update button is disabled

• The Update button is enabled when the Add button is clicked, at which time

the Data Control and Add Button should be disabled.

• The Reverse should happen when the update button is clicked

I leave you to set up the enabling and disabling.

4 Apply similar buttons to the Employee Form

Further development...

It is worth taking this further by incorporating the following...

• Checking the Dept field in an employee record is Valid

• The ability to cancel adding a new record

Page 26: Visual Basic 5-6 Course Part 9

Visual Basic Book 9 © Mark Collins 1999 Page 25

Exercise 2

In this exercise we will develop a form that allows you to display any recordset in a grid.

1 Start a new project called DataGrid.

2 Place a single grid control on your form. Set the following properties...

Object Property Value

Form Name frmDataGrid

Caption DataGrid

Grid Control Name grdData

DatabaseName ...\EMPLOYEE.MDB

3 Next some code to resize the Grid to fill the form...

Sub Form_Resize ()

grdData.Top = 0

grdData.Left = 0

grdData.Width = Me.ScaleWidth

grdData.Height = Me.ScaleHeight

End Sub

4 Now for the heart of this application, create a General sub procedure called DoGrid.

This procedure will perform the following tasks...

• Open the Database

• Establish a Recordset variable using an SQL query

• Extract Field details

• Place Field names in Grid heading

• Automatically adjust Column Widths

• Loop through the records, creating a Tab-delimited string for each and adding

that string to the grid

• Fix first row of Grid & tidy up

Before seeing the code, consider how each of these tasks could be performed. The

code for this procedure is overleaf...

5 Set up your Form Load procedure...

Sub Form_Load ()

Form_Resize subDoGrid

End Sub

Page 27: Visual Basic 5-6 Course Part 9

Visual Basic Book 9 © Mark Collins 1999 Page 26

Sub DoGrid ()

Dim dbEMP As Database

Dim dsAny As Recordset

Dim fd() As Field

Dim NewRecord As String ' String for AddItem

Dim TB As String, cw As Integer

Static SQLQuery(3) As String ' Array of queries

TB = Chr$(9) ' Set up Tab character

Set dbEMP = OpenDatabase("e:\vb-bits\projects\employee\employee.mdb")

SQLQuery(1) = "SELECT * FROM Dept "

SQLQuery(2) = "SELECT * FROM Employee"

SQLQuery(3) = "SELECT [Emp Name], [Dept Name], Salary "

SQLQuery(3) = SQLQuery(3) & "FROM Dept, Employee "

SQLQuery(3) = SQLQuery(3) & "WHERE Dept.[Dept Code] = Employee.Dept"

Set dsAny = dbEMP.CreateDynaset(SQLQuery(3)) ‘ Change as needed

' establish fields

ReDim fd(dsAny.Fields.Count)

For i = 0 To dsAny.Fields.Count - 1

Set fd(i) = dsAny.Fields(i)

NewRecord = NewRecord & fd(i).SourceField & TB

Next

'Set up Grid Columns & Headings

grdData.FixedCols = 0

grdData.FixedRows = 0

grdData.Rows = 1

grdData.Cols = dsAny.Fields.Count

grdData.AddItem NewRecord, 0 ' setup headings

'Set Column Widths

For i = 0 To dsAny.Fields.Count - 1

If Len(fd(i).Value) > Len(fd(i).SourceField) Then

cw = Len(fd(i).Value)

Else

cw = Len(fd(i).SourceField)

End If

grdData.ColWidth(i) = cw * 160

Next

'Retrieve Data

dsAny.MoveFirst

While Not dsAny.EOF

NewRecord = ""

For i = 0 To dsAny.Fields.Count - 1

NewRecord = NewRecord & fd(i).Value & TB

Next

'Add record to grid

grdData.AddItem NewRecord, 1

dsAny.MoveNext

Wend

' Tidy up grid, remove extra column & fix Heading

grdData.FixedRows = 1

grdData.Cols = grdData.Cols - 1

End Sub