vb6 db manual

270
Visual Basic and Databases LAP II ISPGAYA

Upload: rifky-raymond

Post on 01-Dec-2015

151 views

Category:

Documents


16 download

TRANSCRIPT

Page 1: VB6 DB Manual

Visual Basic and Databases

LAP II ISPGAYA

Page 2: VB6 DB Manual

Visual Basic and Databases

© LAP II

ii

Notice

This guide was developed for the course, “Visual Basic and Databases,”. It is not intended to be a complete reference to Visual Basic. Consult the Microsoft documentation that comes with your particular version of Visual Basic for detailed reference information. This guide refers to several software and hardware products by their trade names. These references are for informational purposes only and all trademarks are the property of their respective companies.

Page 3: VB6 DB Manual

Contents

© LAP II

iii

Visual Basic and Databases

Contents

1. Introducing Visual Basic and Databases Preview ......................................................................................................1-1 Course Objectives......................................................................................1-2 Course Requirements ................................................................................1-3 What is a Database?..................................................................................1-4 Where Does Visual Basic Fit In?................................................................1-6 Building a Visual Basic Application ............................................................1-8 Structure of a Visual Basic Application .................................................1-8 Steps in Developing Application ...........................................................1-9 Drawing the User Interface and Setting Properties...............................1-9 Setting Properties of Controls at Design Time....................................1-13 Setting Properties at Run-Time ..........................................................1-14 How Names are Used in Object Events .............................................1-14 Writing Code ............................................................................................1-15 Review of Variables............................................................................1-15 Visual Basic Data Types.....................................................................1-15 Variable Declaration ...........................................................................1-16 Example 1. Mailing List Application..........................................................1-18 Summary .................................................................................................1-25 2. Introduction to Databases Review and Preview ..................................................................................2-1 Database Structure and Terminology ........................................................2-2 Relational Databases.................................................................................2-3 Sample Relational Database......................................................................2-4 Sample Database Structure.......................................................................2-7 Virtual Database Tables.............................................................................2-8 Creating a Database ................................................................................2-10 Summary .................................................................................................2-11

Page 4: VB6 DB Manual

Visual Basic and Databases

© LAP II

iv

3. Database Connection with the DAO Data Control Review and Preview ..................................................................................3-1 DAO or ADO – What’s the Difference? ......................................................3-2 DAO Data Control ......................................................................................3-3 DAO Data Control Properties ...............................................................3-4 Recordset Object..................................................................................3-5 Data Bound Controls..................................................................................3-6 Data Bound Control Properties.............................................................3-6 Example 3-1. Accessing the Books Database ...........................................3-8 DAO Data Control Events ........................................................................3-11 DAO Data Control Methods .....................................................................3-11 DAO Data Control Recordset Properties .................................................3-12 DAO Data Control Recordset Methods ....................................................3-13 DAO Data Control Recordset Navigation.................................................3-14 Quick Example 1 - Recordset Navigation ...........................................3-15 Summary .................................................................................................3-17 Exercise 3. Northwind Traders Database ................................................3-18

Page 5: VB6 DB Manual

Contents

© LAP II

v

4. Database Connection with ADO Technology Review and Preview ..................................................................................4-1 ADO Data Control ......................................................................................4-2 ADO Data Control Properties ...............................................................4-3 ConnectionString Property....................................................................4-4 Recordset Object..................................................................................4-5 Data Bound Controls..................................................................................4-6 Data Bound Control Properties.............................................................4-6 Example 4-1. Accessing the Books Database ...........................................4-8 ADO Data Control Events ........................................................................4-11 ADO Data Control Methods .....................................................................4-12 ADO Data Control Recordset Properties .................................................4-12 ADO Data Control Recordset Methods ....................................................4-13 ADO Data Control Recordset Navigation.................................................4-14 Quick Example 1 - Recordset Navigation ...........................................4-15 DAO or ADO – What’s the Difference? ....................................................4-17 ADO Data Environment ...........................................................................4-18 Connection Object ..............................................................................4-19 Command Object................................................................................4-19 Quick Example 2 – Use of ADO Data Environment............................4-20 Data Bound Controls with the Data Environment.....................................4-23 Example 4-2. Drag and Drop Controls................................................4-24 Recordsets in the Data Environment .......................................................4-27 Quick Example 3 – Record Navigation with the Data Environment ....4-28 DAO to ADO – ADO to DAO....................................................................4-30 Summary .................................................................................................4-32 Exercise 4-1. Northwind Traders Database .............................................4-33 Exercise 4-2. Data Environment with Northwind Traders Database ........4-36

Page 6: VB6 DB Manual

Visual Basic and Databases

© LAP II

vi

5. Database Queries with SQL Review and Preview ..................................................................................5-1 SQL Background........................................................................................5-2 Basics of SQL ............................................................................................5-3 Where Does SQL Fit In Visual Basic? .......................................................5-5 SQL with the DAO Data Control.................................................................5-6 Quick Example 1 - SQL with the DAO Data Control .............................5-7 SQL with the ADO Data Control.................................................................5-9 Quick Example 2 - SQL with the ADO Data Control ..........................5-10 SQL with the ADO Data Environment ......................................................5-12 Quick Example 3 - SQL with the ADO Data Environment ..................5-14 Example 5-1. SQL Tester ........................................................................5-17 A Brief (Hopefully) Interlude for Visual Basic 6 Users ..............................5-18 SELECT/FROM SQL Statement ..............................................................5-23 ORDER BY Clause ..................................................................................5-25 WHERE Clause .......................................................................................5-28 Single Table WHERE Clause...................................................................5-29 Multiple Table WHERE Clause ................................................................5-32 INNER JOIN Clause ................................................................................5-37 OUTER JOIN Clause ...............................................................................5-41 Visual Basic Functions with SQL .............................................................5-43 SQL Aggregate Functions........................................................................5-45 SQL Construction Tools...........................................................................5-47 Building SQL Commands in Code ...........................................................5-51 Example 5-2. Searching the Books Database ....................................5-52 Summary .................................................................................................5-58 Exercise 5. Northwind Traders Database ................................................5-59

Page 7: VB6 DB Manual

Contents

© LAP II

vii

6. Visual Basic Interface Design Review and Preview ..................................................................................6-1 Interface Design Philosophy ......................................................................6-2 Example 6-1. Mailing List Revisited......................................................6-4 Visual Basic Standard Controls..................................................................6-5 Form Control.........................................................................................6-5 Command Button Control .....................................................................6-6 Label Control ........................................................................................6-7 Text Box Control ...................................................................................6-8 Check Box Control................................................................................6-9 Option Button Control .........................................................................6-10 Frame Control.....................................................................................6-10 Picture Box Control.............................................................................6-11 Image Control .....................................................................................6-11 Example 6-2. Authors Table Input Form.............................................6-12 Message Box ...........................................................................................6-19 Example 6-3. Authors Table Input Form (Message Box) ....................6-22 Application State ......................................................................................6-24 Example 6-4. Authors Table Input Form (Application State)...............6-26 Entry Validation........................................................................................6-29 Example 6-5. Authors Table Input Form (Entry Validation).................6-31 Input Validation ........................................................................................6-32 Example 6-6. Authors Table Input Form (Input Validation) .................6-34 Error Trapping and Handling....................................................................6-37 Example 6-7. Authors Table Input Form (Error Trapping and Handling) ............................................................6-42 On-Line Help Systems .............................................................................6-43 Example 6-8. Authors Table Input Form (On-Line Help Systems)......6-51 Application Testing...................................................................................6-54 Custom Controls ......................................................................................6-55 Masked Edit Control.................................................................................6-56 Quick Example 1 – Masked Edit Control ............................................6-57 UpDown Control.......................................................................................6-58 Quick Example 2 – UpDown Control ..................................................6-59 Tabbed Dialog Control .............................................................................6-61 Quick Example 3 – Tabbed Dialog Control.........................................6-62 Toolbar Control ........................................................................................6-63 Quick Example 4 – Toolbar Control ....................................................6-64 Data Bound List Control ...........................................................................6-66 Quick Example 5 – Data Bound List Control.......................................6-68 Data Bound Combo Control .....................................................................6-70

Page 8: VB6 DB Manual

Visual Basic and Databases

© LAP II

viii

6. Visual Basic Interface Design (continued) Data Bound Grid Control..........................................................................6-71 Quick Example 6 – Data Bound Grid Control .....................................6-72 Data Bound FlexGrid Control ...................................................................6-73 Quick Example 7 – Data Bound FlexGrid Control...............................6-74 Calendar Control......................................................................................6-75 Quick Example 8 – Calendar Control .................................................6-76 Common Dialog Control...........................................................................6-77 Quick Example 9 – Common Dialog Control ......................................6-79 Additional ADO Custom Controls.............................................................6-81 Hierarchical FlexGrid Control ...................................................................6-82 Quick Example 10 – Hierarchical FlexGrid Control.............................6-83 Chart Control............................................................................................6-84 Quick Example 11 – Chart Control .....................................................6-85 Month View Control..................................................................................6-86 Quick Example 12 – Month View Control ...........................................6-87 Date Time Picker Control .........................................................................6-88 Quick Example 13 – Date Time Picker Control...................................6-89 Data Repeater Control .............................................................................6-90 Example 6-9. Data Repeater Control..................................................6-91 Summary .................................................................................................6-96 Exercise 6. Publisher Table Input Form ...................................................6-97 Build Interface.....................................................................................6-98 Add Message Box(es) ......................................................................6-102 Code Application State .....................................................................6-103 Perform Entry Validation...................................................................6-104 Perform Input Validation ...................................................................6-105 Add Error Trapping and Handling .....................................................6-105 Add On-Line Help System ................................................................6-106 Application Testing ...........................................................................6-107

Page 9: VB6 DB Manual

Contents

© LAP II

ix

7. Database Management Review and Preview ..................................................................................7-1 Database Management with the DAO Data Control...................................7-2 Editing Records with the DAO Data Control...............................................7-3 Example 7-1. Editing Records with the DAO Data Control ...................7-6 Adding Records with the DAO Data Control ............................................7-13 Example 7-2. Adding Records with the DAO Data Control .................7-15 Deleting Records with the DAO Data Control ..........................................7-18 Example 7-3. Deleting Records with the DAO Data Control ...............7-20 Database Management with the ADO Data Control.................................7-22 Editing Records with the ADO Data Control.............................................7-23 Example 7-4. Editing Records with the ADO Data Control .................7-26 Adding Records with the ADO Data Control ............................................7-33 Example 7-5. Adding Records with the ADO Data Control .................7-35 Deleting Records with the ADO Data Control ..........................................7-38 Example 7-6. Deleting Records with the ADO Data Control ...............7-40 Database Management with the ADO Data Environment ........................7-42 Editing Records with the ADO Data Environment ....................................7-43 Example 7-7. Editing Records with the ADO Data Environment.........7-45 Adding Records with the ADO Data Environment....................................7-54 Example 7-8. Adding Records with the ADO Data Environment ........7-56 Deleting Records with the ADO Data Environment..................................7-59 Example 7-9. Deleting Records with the ADO Data Environment ......7-61 Finding Records in a Database................................................................7-63 Finding Records with the DAO Data Control............................................7-64 Quick Example 1 - Finding Records with the DAO Data Control ........7-66 Finding Records with the ADO Data Control............................................7-67 Quick Example 2 - Finding Records with the ADO Data Control ........7-69 Finding Records with the ADO Data Environment ...................................7-70 Quick Example 3 - Finding Records with the ADO Data Environment..............................7-72 Modifying Records in Code......................................................................7-73 Quick Example 4 – Accessing Records in Code.................................7-75 Stopping a Database Application .............................................................7-76 Example 7-10 – Stopping a Database Application..............................7-78 Example 7-11. Authors Table Input Form ................................................7-80 Additional Navigation Capabilities.......................................................7-81 Editing Records ..................................................................................7-83 Adding Records ..................................................................................7-87 Deleting Records ................................................................................7-94 Stopping the Application .....................................................................7-95

Page 10: VB6 DB Manual

Visual Basic and Databases

© LAP II

x

Visual Basic and Databases

1. Introducing Visual Basic and Databases

Preview • In this first chapter, we will do a quick overview of what the course entails. We

will discuss what you need to complete the course. We’ll take a brief look at what databases are, where they are used, and how Visual Basic is used with databases. And, we’ll review the Visual Basic development environment and the steps followed to build an application in Visual Basic.

Page 11: VB6 DB Manual

Contents

© LAP II

xi

Course Objectives ⇒ Understand the benefits of using Microsoft Visual Basic to build a ‘front-end’

interface as a database programming tool ⇒ Learn database structure, terminology, and proper database design ⇒ Learn how to connect to a database using the Visual Basic DAO (data access

object) control ⇒ Use the ADO (ActiveX data object) data control and data environment to

connect to a database (Visual Basic 6 only) ⇒ Learn the use of Visual Basic data bound controls ⇒ Learn to make database queries using SQL (structured query language) ⇒ Understand proper database search techniques ⇒ Learn how to use the Visual Data Manager to create a database ⇒ Learn database management techniques ⇒ Learn to create and produce database reports ⇒ Learn how to distribute a Visual Basic database application ⇒ Understand connection to remote databases ⇒ Introduce other advanced database concepts

Page 12: VB6 DB Manual

Visual Basic and Databases

© LAP II

xii

Course Requirements • An obvious requirement is a Windows-based computer with Windows 95,

Windows 98, Windows 2000, Windows Me, Windows NT, or Windows XP installed, as well as Visual Basic. The student should be familiar with the basics of using the Windows operating system.

• Visual Basic and Databases requires some edition of Visual Basic 5 or

Visual Basic 6. There are two controls used by Visual Basic to interact with databases: the DAO (data access object) control and the ADO (ActiveX data object) control. Both controls will be discussed in this course. You should be aware, however, that the ADO control is available only with Visual Basic 6

• Most examples presented in the course notes are done using the Professional

Edition of Visual Basic 6. Hence, if you are using Visual Basic 5 or another edition of Visual Basic 6, some of your screens may differ from the ones seen in the notes.

• No knowledge of databases or how to work with databases is presumed.

Adequate introductory material is presented. Even if you’ve worked with databases before, it is suggested you read through this introductory information to become acquainted with the nomenclature used by the author for databases and their component parts.

• This course does not teach you how to build a Visual Basic application. It is

assumed that the student has a basic understanding of the Visual Basic development environment and knows the steps involved in building a Visual Basic application. You should feel quite comfortable with building the example application at the end of this first chapter. If not, our company, KIDware, offers several tutorials that teach this information. Please visit our web site or contact us for more information.

Page 13: VB6 DB Manual

Contents

© LAP II

xiii

What is a Database? • A database is a collection of information. This information is stored in a very

structured manner. By exploiting this known structure, we can access and modify the information quickly and correctly.

• In this information age, databases are everywhere:

⇒ When you go to the library and look up a book on their computer, you are accessing the library’s book database.

⇒ When you go on-line and purchase some product, you are accessing the web merchant’s product database.

⇒ Your friendly bank keeps all your financial records on their database. When you receive your monthly statement, the bank generates a database report.

⇒ When you call to make a doctor appointment, the receptionist looks into their database for available times.

⇒ When you go to your car dealer for repairs, the technician calls up your past work record on the garage database.

⇒ At the grocery store, when the checker scans each product, the price is found in the store’s database, where inventory control is also performed.

⇒ When you are watching a baseball game on television and the announcer tells you that “the batter is hitting .328 against left-handed pitchers whose mother was born in Kentucky on a Tuesday morning,” that useless information is pulled from the team’s database (apologies to our foreign readers who don’t understand the American game of baseball!).

• You can surely think of many more places that databases enter your life. The

idea is that they are everywhere. And, each database requires some way for a user to interact with the information within. Such interaction is performed by a database management system (DBMS).

Page 14: VB6 DB Manual

Visual Basic and Databases

© LAP II

xiv

• The tasks of a DBMS are really quite simple. In concept, there are only a few things you can do with a database: 1. View the data 2. Find some data of interest 3. Modify the data 4. Add some data 5. Delete some data

There are many commercial database management systems that perform these tasks. Programs like Access (a Microsoft product) and Oracle are used world-wide. In this course, we look at using Visual Basic as a DBMS.

• Examples where you might use Visual Basic as a DBMS:

⇒ Implementing a new application that requires management of a database

⇒ Connecting to an existing database ⇒ Interacting with a database via the internet

• In a DBMS, the database may be available locally on your (or the user’s)

computer, available on a LAN (local area network) shared by multiple users, or only available on a web server via the Internet. In this course, we spend most of our time looking at local databases, but access with remote databases is addressed.

• We will look at databases in more depth in the next chapter. You will see that

databases have their own vocabulary. Now, let’s take a look at how Visual Basic fits into the database management system.

Page 15: VB6 DB Manual

Contents

© LAP II

xv

Where Does Visual Basic Fit In? • For database management, we say our Visual Basic application acts as a

front-end to the database. This means the Visual Basic application provides the interface between the user and the database. This interface allows the user to tell the database what he or she needs and allows the database to respond to the request displaying the requested information in some manner.

• A Visual Basic application cannot directly interact with a database. There are

two intermediate components between the application and the database: the data control and the database engine:

• The data control is a Visual Basic object that connects the application to the

database via the database engine. It is the conduit between the application and the engine, passing information back and forth between the two.

• The database engine is the heart of a Visual Basic database management

system. It is the actual software that does the management. Having this engine saves programmers a lot of work. The database engine native to Visual Basic is known as the Jet engine. It is the same engine used by Microsoft Access for database management. Hence, it is primarily used to work with Access databases, but it can also work with others.

Page 16: VB6 DB Manual

Visual Basic and Databases

© LAP II

xvi

• As mentioned, the Jet engine will save us lots of work. An observation that illustrates the power of using Visual Basic as a front-end for database management systems:

Using Visual Basic, it requires less code to connect to an existing database, view all information within that database, and modify any and all information within that database, than it does to add two numbers together.

That’s right - all the database tasks mentioned above can be done without writing one line of code! That’s the power of the Jet database engine!

• So, if the Jet engine is so powerful and is the same engine used by Microsoft

Access, why not just use Access as a DBMS instead of writing a custom Visual Basic application? There are two primary advantages to using Visual Basic as a DBMS instead of Access:

1. Your users don’t need to have Access installed on their computers or

know how to use Access. 2. By building a custom front-end, you limit what your user can do with

the information within the database. Under normal operation, Access provides no such limits.

• So, in this course, we will look at how to build Visual Basic applications that

operate as front-ends to databases. Research has shown that over half of all Visual Basic applications involve working with databases. We will look at how to make our applications into complete database management systems, being able to view, search, modify, add, and/or delete database information.

• Before going any further, let’s review the steps in building a Visual Basic

application and then build a simple application for practice.

Page 17: VB6 DB Manual

Contents

© LAP II

xvii

Control 1

Control 3

Control 2

Form 2 (.FRM)

Control 1

Control 3

Control 2

Form 3 (.FRM) Module 1 (.BAS)

Building a Visual Basic Application • In the remainder of this chapter, we will provide an overview of a Visual Basic

application and how the Visual Basic development environment is used to develop an application. This should provide you with some idea of what knowledge you need to possess to proceed in this course and introduce the terminology used by the author to describe a Visual Basic application.

Structure of a Visual Basic Application Project (.VBP) Application (Project - saved as a file with a .VBP extension) is made up of: ⇒ Forms - Windows that you create for user interface (saved as a file with a

.FRM extension). ⇒ Controls - Graphical features drawn on forms to allow user interaction (text

boxes, labels, scroll bars, command buttons, etc.) (Forms and Controls are also called objects.)

⇒ Properties - Every characteristic of a form or control is specified by a property. Example properties include names, captions, size, color, position, and contents. Visual Basic applies default properties. You can change properties at design time or run time.

⇒ Methods - Built-in procedures that can be invoked to impart some action to a particular object.

⇒ Event Procedures - Code related to some object. This is the code that is executed when a certain event occurs.

⇒ General Procedures - Code not related to objects. This code must be invoked by the application.

⇒ Modules - Collection of general procedures, variable declarations, and constant definitions used by application (saved as a file with a .BAS extension).

Control 1

Control 3

Control 2

Form 1 (.FRM)

Page 18: VB6 DB Manual

Visual Basic and Databases

© LAP II

xviii

Steps in Developing Application • There are three primary steps involved in building a Visual Basic application:

1. Draw the user interface 2. Assign properties to controls 3. Write code for event procedures. Develop any needed general procedures.

We’ll look at each step.

Drawing the User Interface and Setting Properties • Visual Basic operates in three modes.

⇒ Design mode - used to build application ⇒ Run mode - used to run the application ⇒ Break mode - application halted and debugger is available

We focus here on the design mode.

• Six windows should appear when you start Visual Basic. If any of these

windows do not appear, they may be accessed using the main window menu View item.

⇒ The Main Window consists of the title bar, menu bar, and toolbar.

The title bar indicates the project name, the current Visual Basic operating mode, and the current form. The menu bar has drop-down menus from which you control the operation of the Visual Basic environment. The toolbar has buttons that provide shortcuts to some of the menu options (ToolTips indicate their function). The main window also shows the location of the current form relative to the upper left corner of the screen (measured in twips) and the width and length of the current form.

Page 19: VB6 DB Manual

Contents

© LAP II

xix

⇒ The Form Window is central to developing Visual Basic applications. It is where you draw your application.

⇒ The Toolbox is the selection menu for controls (objects) used in your application.

Pointer

Label

Frame

Check Box

Combo Box

Horizontal Scroll Bar

Timer

Directory List Box

Shapes

Image Box

Object Linking Embedding

Picture Box

Text Box

Command Button

Option Button

List Box

Vertical Scroll Bar

Drive List Box

File List Control

Line Control

DAO Data Control

Page 20: VB6 DB Manual

Visual Basic and Databases

© LAP II

xx

⇒ The Properties Window is used to establish initial property values for objects. The drop-down box at the top of the window lists all objects in the current form. Two views are available: Alphabetic and Categorized. Under this box are the available properties for the currently selected object.

⇒ The Form Layout Window shows where (upon program execution) your form will be displayed relative to your monitor’s screen:

Page 21: VB6 DB Manual

Contents

© LAP II

xxi

⇒ The Project Explorer Window displays a list of all forms and modules making up your application. You can also obtain a view of the Form or Code windows (window containing the actual Basic coding) from the Project Explorer window.

• As mentioned, the user interface is ‘drawn’ in the form window. There are two

ways to place controls on a form:

1. Double-click the tool in the toolbox and it is created with a default size on the form. You can then move it or resize it.

2. Click the tool in the toolbox, and then move the mouse pointer to the

form window. The cursor changes to a crosshair. Place the crosshair at the upper left corner of where you want the control to be, press the left mouse button and hold it down while dragging the cursor toward the lower right corner. When you release the mouse button, the control is drawn. This approach must be used to place controls in a frame or picture box control.

• To move a control you have drawn, click the object in the form window and

drag it to the new location. Release the mouse button. • To resize a control, click the object so that it is select and sizing handles

appear. Use these handles to resize the object.

Page 22: VB6 DB Manual

Visual Basic and Databases

© LAP II

xxii

Setting Properties of Controls at Design Time • Each form and control has properties assigned to it by default when you start

a new project. There are two ways to display the properties of an object. The first way is to click on the object (form or control) in the form window. Then, click on the Properties Window or the Properties Window button in the tool bar. The second way is to first click on the Properties Window. Then, select the object from the Object box in the Properties Window. Shown is the Properties Window for a new application:

The drop-down box at the top of the Properties Window is the Object box. It displays the name of each object in the application as well as its type. This display shows the Form object. The Properties list is directly below this box. In this list, you can scroll through the list of properties for the selected object. You may select a property by clicking on it. Properties can be changed by typing a new value or choosing from a list of predefined settings (available as a drop down list). Properties can be viewed in two ways: Alphabetic and Categorized. A very important property for each object is its name. The name is used by Visual Basic to refer to a particular object in code.

• A convention has been established for naming Visual Basic objects. This convention is to use a three-letter prefix (depending on the object) followed by a name you assign. A few of the prefixes are (we’ll see more as we progress in the course):

Object Prefix Example Form frm frmWatch Command Button cmd, btn cmdExit, btnStart Label lbl lblStart, lblEnd Text Box txt txtTime, txtName Menu mnu mnuExit, mnuSave Check box chk chkChoice Data control dat datExample

Page 23: VB6 DB Manual

Contents

© LAP II

xxiii

• Object names can be up to 40 characters long, must start with a letter, must contain only letters, numbers, and the underscore (_) character. Names are used in setting properties at run time and also in establishing procedure names for object events.

Setting Properties at Run Time • In addition to setting control properties in design mode, you can set or modify

properties while your application is running (run mode). To do this, you must write some code. The code format is:

ObjectName.Property = NewValue

Such a format is referred to as dot notation. For example, to change the BackColor property of a form name frmStart, we'd type:

frmStart.BackColor = vbBlue

• Using the three-letter prefix when naming an object and using an appropriate

name makes reading such code easier and more meaningful. How Names are Used in Object Events • The names you assign to objects are used by Visual Basic to set up a

framework of event-driven procedures for you to add code to. The format for each of these subroutines (all object event procedures in Visual Basic are subroutines) is:

Sub ObjectName_Event (Optional Arguments) . . End Sub

Visual Basic provides the Sub line with its arguments (if any) and the End Sub statement. You provide any needed code.

• Using the three-letter prefix when naming an object and using a meaningful

name makes finding appropriate event procedures a simpler task.

Page 24: VB6 DB Manual

Visual Basic and Databases

© LAP II

xxiv

Writing Code • The last step in building a Visual Basic application is to write code using the

BASIC language. This is the most time consuming task in any Visual Basic application, not just ones involving databases. As objects are added to the form, Visual Basic automatically builds a framework of all event procedures. We simply add code to the event procedures we want our application to respond to. And, if needed, we write general procedures.

• Code is placed in the code window. At the top of the code window are two

boxes, the object (or control) list and the procedure list. Select an object and the corresponding event procedure. A blank procedure will appear in the window where you write BASIC code.

Review of Variables • Variables are used by Visual Basic to hold information needed by your

application. Rules used in naming variables:

⇒ No more than 40 characters ⇒ They may include letters, numbers, and underscore (_) ⇒ The first character must be a letter ⇒ You cannot use a reserved word (word needed by Visual Basic)

Visual Basic Data Types ⇒ Boolean (True or False) ⇒ Integer (Whole numbers) ⇒ Long (Large whole numbers) ⇒ Single (Floating point numbers) ⇒ Double (Large floating point numbers) ⇒ Currency ⇒ Date ⇒ Object (yes, objects can be variables!) ⇒ String (Used for many control properties) ⇒ Variant (A chameleon, becomes what it needs to be)

Page 25: VB6 DB Manual

Contents

© LAP II

xxv

Variable Declaration • There are three ways for a variable to be typed (declared):

1. Default (Variant type) 2. Implicit (old technology) 3. Explicit

• There are many advantages to explicitly typing variables. Primarily, we insure

all computations are properly done, mistyped variable names are easily spotted, and Visual Basic will take care of insuring consistency in upper and lower case letters used in variable names. Because of these advantages, and because it is good programming practice, we will explicitly type all variables.

• To explicitly type a variable, you must first determine its scope. There are four levels of scope:

⇒ Procedure level ⇒ Procedure level, static ⇒ Form and module level ⇒ Global level

• Within a procedure, variables are declared using the Dim statement:

Dim MyInt As Integer Dim MyDouble As Double Dim MyString As String, YourString As String

Procedure level variables declared in this manner do not retain their value once a procedure terminates.

• To make a procedure level variable retain its value upon exiting the procedure,

replace the Dim keyword with Static:

Static MyInt As Integer Static MyDouble As Double

• Form (module) level variables retain their value and are available to all

procedures within that form (module). Form (module) level variables are declared in the declarations part of the general object in the form's (module's) code window. The Dim keyword is used:

Dim MyInt As Integer Dim MyDate As Date

Page 26: VB6 DB Manual

Visual Basic and Databases

© LAP II

xxvi

• Global level variables retain their value and are available to all procedures within an application. Module level variables are declared in the declarations part of the general object of a module's code window. (It is advisable to keep all global variables in one module.) Use the Global keyword:

Global MyInt As Integer Global MyDate As Date

• What happens if you declare a variable with the same name in two or more

places? More local variables shadow (are accessed in preference to) less local variables. For example, if a variable MyInt is defined as Global in a module and declared local in a routine MyRoutine, while in MyRoutine, the local value of MyInt is accessed. Outside MyRoutine, the global value of MyInt is accessed.

• Example of Variable Scope:

Module1 Global X As Integer Form1 Form2 Dim Y As Integer Dim Z As Single Sub Routine1() Sub Routine3() Dim A As Double Dim C As String . . . . End Sub End Sub Sub Routine2() Static B As Double . . End Sub

Procedure Routine1 has access to X, Y, and A (loses value upon termination) Procedure Routine2 has access to X, Y, and B (retains value) Procedure Routine3 has access to X, Z, and C (loses value)

Page 27: VB6 DB Manual

Contents

© LAP II

xxvii

Example 1

Mailing List Application In this example, we will build a Visual Basic application that could function as a database interface. The application allows the entry of information (names and addresses) to build a mailing list. An added feature is a timer that keeps track of the time spent entering addresses. After each entry, rather than write the information to a database (as we would normally do), the input information is simply displayed in a Visual Basic message box. We present this example to illustrate the steps in building an application. If you feel comfortable building this application and understanding the corresponding code, you probably possess the Visual Basic skills needed to proceed with this course. 1. Start a new project. Place two frames on the form (one for entry of address

information and one for the timing function). In the first frame, place five labels, five text boxes, and two command buttons. In the second frame, place a label control, a timer control and three command buttons. Remember you need to ‘draw’ controls into frames. Resize and position controls so your form resembles this:

2. Set properties for the form and controls (these are just suggestions – make any

changes you might like):

Form1: Name frmMailingList BorderStyle 1-Fixed Single Caption Mailing List Application

Page 28: VB6 DB Manual

Visual Basic and Databases

© LAP II

xxviii

Frame1: Name fraMail Caption Address Information Enabled False Label1: Caption Name Label2: Caption Address Label3: Caption City Label4: Caption State Label5: Caption Zip Text1: Name txtInput Index 0 (a control array) TabIndex 1 Text [blank it out] Text2: Name txtInput Index 1 TabIndex 2 Text [blank it out] Text3: Name txtInput Index 2 TabIndex 3 Text [blank it out] Text4: Name txtInput Index 3 TabIndex 4 Text [blank it out]

Page 29: VB6 DB Manual

Contents

© LAP II

xxix

Text5: Name txtInput Index 4 TabIndex 5 Text [blank it out] Command1: Name cmdAccept Caption &Accept TabIndex 6 Command2: Name cmdClear Caption &Clear Frame2: Name fraTime Caption Elapsed Time Label6: Name lblElapsedTime Alignment 2-Center Backcolor White BorderStyle 1-Fixed Single Caption 00:00:00 FontBold True FontSize 14 Timer1: Name timSeconds Enabled False Interval 1000 Command3: Name cmdStart Caption &Start Command4: Name cmdPause Caption &Pause Enabled False

Page 30: VB6 DB Manual

Visual Basic and Databases

© LAP II

xxx

Command5: Name cmdExit Caption E&xit

When done, the form should appear something like this:

3. Put these lines in the General Declarations area of the code window:

Option Explicit Dim ElapsedTime As Variant Dim LastNow As Variant

4. Put these lines in the Form_Load event procedure:

Private Sub Form_Load() ElapsedTime = 0 End Sub

5. Put this code in the txtInput_KeyPress event procedure:

Private Sub txtInput_KeyPress(Index As Integer, KeyAscii As Integer) 'Check for return key If KeyAscii = vbKeyReturn Then If Index = 4 Then cmdAccept.SetFocus Else txtInput(Index + 1).SetFocus End If End If

Page 31: VB6 DB Manual

Contents

© LAP II

xxxi

'In Zip text box, make sure only numbers or backspace pressed If Index = 4 Then If (KeyAscii >= Asc("0") And KeyAscii <= Asc("9")) Or KeyAscii = vbKeyBack Then Exit Sub Else KeyAscii = 0 End If End If End Sub

Note the line beginning with ‘If (KeyAscii >= Asc(“0”) And ...’ is so long that the word processor wraps the line around at the margin. Type this as one long line, not two separate lines or review the use of the Visual Basic line continuation character (_). Be aware this happens quite often in these notes when actual code is being presented.

6. Put this code in the cmdAccept_Click event procedure:

Private Sub cmdAccept_Click() Dim S As String, I As Integer 'Accept button clicked - form label and output in message box 'Make sure each text box has entry For I = 0 To 4 If txtInput(I).Text = "" Then MsgBox "Each box must have an entry!", vbInformation + vbOKOnly, "Error" Exit Sub End If Next I S = txtInput(0).Text + vbCrLf + txtInput(1).Text + vbCrLf S = S + txtInput(2).Text + ", " + txtInput(3).Text + " " + txtInput(4).Text MsgBox S, vbOKOnly, "Mailing Label" Call cmdClear_Click End Sub

Page 32: VB6 DB Manual

Visual Basic and Databases

© LAP II

xxxii

7. Put this code in the cmdClear_Click event procedure:

Private Sub cmdClear_Click() Dim I As Integer 'Clear all text boxes For I = 0 To 4 txtInput(I).Text = "" Next I txtInput(0).SetFocus End Sub

8. Put this code in the cmdStart_Click event procedure:

Private Sub cmdStart_Click() 'Start button clicked 'Disable start and exit buttons 'Enabled pause button cmdStart.Enabled = False cmdExit.Enabled = False cmdPause.Enabled = True 'Establish start time and start timer control LastNow = Now timSeconds.Enabled = True 'Enable mailing list frame fraMail.Enabled = True txtInput(0).SetFocus End Sub

9. Put this code in the cmdPause_Click event procedure:

Private Sub cmdPause_Click() 'Pause button clicked 'Disable pause button 'Enabled start and exit buttons cmdPause.Enabled = False cmdStart.Enabled = True cmdExit.Enabled = True 'Stop timer timSeconds.Enabled = False 'Disable editing frame fraMail.Enabled = False End Sub

Page 33: VB6 DB Manual

Contents

© LAP II

xxxiii

10. Put this code in the cmdExit_Click event procedure:

Private Sub cmdExit_Click() 'Exit button clicked End End Sub

11. Put this code in the timSeconds_Timer event procedure:

Private Sub timSeconds_Timer() 'Increase elapsed time and display ElapsedTime = ElapsedTime + Now - LastNow lblElapsedTime.Caption = Format(ElapsedTime, "hh:mm:ss") LastNow = Now End Sub

12. Save the application. Run the application. Make sure it functions as designed.

Note that you cannot enter mailing list information unless the timer is running.

Page 34: VB6 DB Manual

Visual Basic and Databases

© LAP II

xxxiv

Summary • In this chapter, we introduced databases in general terms and how Visual

Basic can be used to develop a front-end application to interact with the database. And, we reviewed the steps involved in building a Visual Basic application.

• In the second chapter, we take a closer look at databases. We look at their

structure, their terminology, and how they are constructed. You may be asking - when do we get to do some programming? The answer - in a couple more chapters. We want to make sure we have a firm foundation in place before diving into actual coding.

Page 35: VB6 DB Manual

Contents

© LAP II

xxxv

Visual Basic and Databases

2. Introduction to Databases Review and Preview • In the last chapter, we looked at a database in very general terms. We learned

that the heart of any Visual Basic database application is the Jet database engine. In this chapter, we provide more details into the structure of databases and how they are created. We will use a sample database to illustrate the concepts presented.

Page 36: VB6 DB Manual

Visual Basic and Databases

© LAP II

xxxvi

Database Structure and Terminology • In simplest terms, a database is a collection of information. This collection is

stored in one or more well-defined tables, or matrices. • The rows in a database table are used to describe similar items. The rows are

referred to as database records. In general, no two rows in a database table will be alike.

• The columns in a database table provide characteristics of the records. These

characteristics are called database fields. Each field contains one specific piece of information. In defining a database field, you specify the data type, assign a length, and describe other attributes. Some field types include Binary, Boolean, Counter, Double, Single, Long, Integer, etc.

• Here is a simple database example:

In this database table, each record represents a single individual. The fields (descriptors of the individuals) include an identification number (ID No), Name, Date of Birth, Height, and Weight.

• Most databases use indexes to allow faster access to the information in the

database. Indexes are sorted lists that point to a particular row in a table. We can create an index for any field we might want to perform a search on. The neat thing about an index is that the Jet database engine (included with Visual Basic) handles all the details. We simply flag a field as an index and the Jet engine does the work.

• A database using a single table is called a flat database. Early database

software worked only with flat databases. And, for simple applications, flat databases may be adequate. For large amounts of data, however, flat databases are cumbersome and become very large, very quickly.

ID No

1

2

3

Bob Jones

Mary Rodgers

Sue Williams

Name Date of Birth

01/04/58

WeightHeight

Field

Record

Table

11/22/61

06/11/57

72

65

68

170

125

130

Page 37: VB6 DB Manual

Contents

© LAP II

xxxvii

Relational Databases • Most databases are made up of many tables stored in a single file. Each table

contains a logical grouping of information with its own records and fields. When using multiple tables within a database, the tables must have some common fields to allow cross-referencing of the tables. The referral of one table to another via a common field is called a relation. Such groupings of tables are called relational databases.

• Relational databases allow us to store vast amounts of data with far simpler

maintenance and smaller storage requirements than the equivalent flat database. As an example, say we had a flat database listing products stocked by a grocery store with several fields describing each product’s manufacturer (manufacturer name, address, phone, ...). If you have 1,000 products made by the same manufacturer, there is much repetition of information in the flat database. And, if the manufacturer changed their phone number, you would have to make that change in 1,000 places! In a relational database, you could use two tables, one for products, one for manufacturers. In the product table, you would simply have a manufacturer ID that would correspond with an ID in the manufacturer table (a relation), which would have that manufacturer’s information. Then, if the phone number changed, you would only have to change one field in the manufacturer table - quite a savings in work! When you break down database tables into simpler tables, the process is known as database normalization.

• Relations among tables in a relational database are established using keys. A

primary key is a field that uniquely identifies a record so it can be referenced from a related table. A foreign key is a field that holds identification values to relate records stored in other tables.

• When one record in one table is linked to only one record in another table, we

say there is a one-to-one relation. When one record in one table links to many records in another table, we say there is a one-to-many relation. And, when many records in one table are linked to many records in another table, we say there is a many-to-many relation.

• In the first few chapters in this course, we will use a sample database that

comes with Visual Basic. This relational database (BIBLIO.MDB) is found in the main Visual Basic directory - you will become very familiar with this database. It is a database of books about computer programming (and databases). Let’s look at its relational structure to illustrate the many new concepts being introduced.

Page 38: VB6 DB Manual

Visual Basic and Databases

© LAP II

xxxviiiSample Relational Database • The books (BIBLIO.MDB) database is made up of four tables:

Authors (6,246 records) Publishers (727 records) Titles (8,569 records) Title Author (16,056 records)

As you look at each table, pay attention to how the tables are logical groupings of information. Examine the record and field structures. In particular, note each field with an ‘ID’ in the name acts as a key to relate one table to another.

• The Authors table contains information about the authors of the books in the

database. The table has three (3) fields: Au_ID, Name, and Year Born:

There are 6,246 different authors in the database.

Page 39: VB6 DB Manual

Contents

© LAP II

xxxix

• The Publishers table contains information about the publishers in the book database. The table has ten (10) fields: PubID, Name, Company Name, Address, City, State, Zip, Telephone, Fax, and Comments:

There are 727 different publishers in the database.

• The Titles table contains information about each book title in the database. The table has eight (8) fields: Title, Year Published, ISBN, PubID, Description, Notes, Subject, and Comments:

There are 8,569 distinct book titles in the database.

Page 40: VB6 DB Manual

Visual Basic and Databases

© LAP II

xl

• The Title Author table contains information relating book titles to authors within the database. It has just two fields: ISBN (International Standard Book Number, a number used by bookstores and libraries to reference books) and Au_ID:

There are 16,056 entries in this table. You may wonder - if there are 8,569 titles in the database, how can there be nearly twice as many entries in this table. The answer is that many books have more than one author and this table lists all the authors for each title.

• There is obviously a lot of information in the books database! This example,

though, is very useful and shows the kind of database we can work with using Visual Basic. It is a well-designed database we can learn from. We will discuss database design in a later chapter, so much of what is discussed here will be very useful information later on. You may be wondering – where did these views of the database tables come from? They were obtained using Microsoft Access. In a couple of more chapters, you will be able to obtain such views using Visual Basic without writing a single line of code!

Page 41: VB6 DB Manual

Contents

© LAP II

xli

Sample Database Structure • Let’s examine the books database a little closer. To help, we’ll use this block

diagram (obtained using Access) that illustrates the database structure:

This diagram shows each table as a separate window listing the corresponding fields. Relations between tables are illustrated via linear links.

• Look at the books database tables. Note each table is a logical grouping of

information. Book publishers are in a single table (Publishers), book titles are in a single table (Titles), and book authors are in a single table (Authors). A well-designed database has such well-defined tables. Well-defined tables make database management a far simpler task.

• Note each table has two types of information: source data and relational data.

Source data is actual information, such as names, phone numbers, and addresses. Relational data are references to data in other tables via keys, such as PubID, ISBN, and Au_ID.

• A primary key defines a unique record. PubID in the Publishers table, ISBN

in the Titles Table, and Au_ID in the Authors table are primary keys. They identify a unique entry in their respective table.

• A foreign key is a piece of relational information in one table that links to

information in another table. In the Titles table, PubID is a foreign key. Using a PubID from this table in conjunction with the PubID primary key in the Publishers table will provide us with complete information about a particular publisher. In the Title Author table, ISBN and Au_ID are foreign keys.

Page 42: VB6 DB Manual

Visual Basic and Databases

© LAP II

xlii

• How the keys are used in the database is shown via the linear links. For example, PubID (a primary key) in the Publishers table relates to the PubID (a foreign key) in the Titles table. The one (1) next to PubID in the Publishers table and the infinity symbol (∞) next to PubID in the Titles table show this is a one-to-many relationship. That is, there is one PubID in the Publishers table, but this value may appear many times in the Titles table.

• There is also a one-to-many relationship between Au_ID (primary key) in the

Authors table and Au_ID (foreign key) in the Title Author table. The relationship between ISBN in the Titles table and ISBN in the Title Author table cannot be determined by Access (indicated by no markings on the linear link). Such indeterminate links will happen occasionally.

Virtual Database Tables • The primary purpose of the books database (BIBLIO.MDB) is to track

information about book titles. Note each table gives us a piece of information about a particular book, but to get all the information about a book, we need all four tables.

• Using the relational data in the four tables, we should be able to obtain a

complete description of any book in the database. Let’s look at one example. Look back at the Titles table and note the first book (a record) listed has this information:

Title 1-2-3 Database Techniques Year Published 1990 ISBN 0-8802234-6-4 PubID 45 Description 29.95 Notes 650.0285536920 Subject [Blank] Comments HF5548.4.L67A52 1989

Taking the ISBN into the Title Author table will provide us with these Au_ID values: Au_ID 2467, 5265, 5266

Page 43: VB6 DB Manual

Contents

© LAP II

xliii

Note the book has three authors. Using these Au_ID values in the Authors table reveals author information: Au_ID=2467 Author Stern, Nancy Year Born [Blank] Au_ID=5265 Author Weil, Bill Year Born [Blank] Au_ID=5266 Author Anderson, Dick Year Born [Blank] A last relational move of using the PubID in the Publishers table will give us complete details about the book publisher: Name QUE CORP Company Name QUE CORP Address 11711 N College Ave, Suite 140 City Carmel State IN Zip 46032 Telephone [Blank] Fax [Blank] Comments [Blank]

• Once done, we know everything there is to know about this one particular book “1-2-3 Database Techniques.” What we essentially have done is formed one huge table with a single record and many, many fields. This new view of the data in the database is called a virtual database table. It is virtual because it doesn’t exist as a native table in the BIBLIO.MDB database – it was formed using the native four tables.

Page 44: VB6 DB Manual

Visual Basic and Databases

© LAP II

xliv

• Making a query of the database created a virtual table above. We asked the database to tell us everything it knew about the book “1-2-3 Database Techniques.” The database responded (well, we really did the work) with all information from its four tables. This is a very common task in database management systems and one we will be doing often in this course, querying the database. With each query of the database, we form a virtual table that contains the results of our query. Our queries will not be as comprehensive as the one made here (show me everything!). Usually, the query will ask for all records that meet some particular criteria. As an example, we might like to query the books database to show us all books published by a specific company. The results of this query would be returned in a virtual table.

• Database queries are made with a specific language named SQL (structured

query language). We will study SQL in a later chapter. For now, be aware that SQL can be used to form virtual tables from a database. These tables show us information of interest from the database. And, with Visual Basic as the front-end, doing a query with SQL is simple. We form the query, pass it on to the Jet database engine (via the data control) and the engine does all the work for us, returning all records that our query requested. It’s like magic! In the first few chapters, we will doing just that – opening the books database and forming virtual tables we can view.

Creating a Database • Before leaving this database introduction, you may be asking yourself – how

are databases like the books database created? How are tables defined? How are fields defined? How are records created?

• Databases are created using commercial applications like Access, dBase,

FoxPro, Oracle, and others. Each of these products has a design mode where you define a table and the fields that are part of the table. You can also enter records into the table using these applications. The books database was built with Access. In the first part of this course, we will work with existing databases and will not be concerned with creating a database.

• Later chapters discuss proper database design and creation of databases. It is

possible to create databases with Visual Basic (we’ll look at how to do this in the final chapter). For now, when we need to create our own database, we will use a product shipped with Visual Basic called the Visual Data Manager. It is a fairly easy-to-use application that will suit our needs quite well. If you know how to use Access, you could also use that when the time for creating a database arises.

Page 45: VB6 DB Manual

Contents

© LAP II

xlv

Summary • In this chapter, we looked at our first database – the books database

(BIBLIO.MDB) that is included with Visual Basic. We studied the structure of a relational database, discussing tables, records, and fields. Relationships using primary and foreign keys were illustrated.

• The concept of a virtual table was introduced. Making a query of the database

forms virtual tables. In the next chapter, we begin learning how to use Visual Basic to connect to a database and process queries to form such virtual tables.

Page 46: VB6 DB Manual

Visual Basic and Databases

© LAP II

xlvi

Visual Basic and Databases

3. Database Connection with the DAO Data Control Review and Preview • At this point, we have looked at databases and how they are structured. We

have seen that the Jet database engine (part of Visual Basic) works between the database and the Visual Basic ‘front-end’ to manage the database. In this chapter, for the first time, we use Visual Basic to connect to a database. This connection is made with the DAO (data access object) data control. Using data bound controls, in conjunction with the DAO control, will allow us to view information in the database.

Page 47: VB6 DB Manual

Contents

© LAP II

xlvii

DAO or ADO – What’s the Difference? • With the introduction of Visual Basic 6, a new data control has emerged – the

ADO (ActiveX Data Object) data control. Past versions of Visual Basic have used the DAO (Data Access Object) data control (also included with Visual Basic 6). So, Visual Basic 6 users (and Visual Basic 5 users, too) may be asking – what’s the difference?

• Both controls do the same thing – provide a tool for working with the Jet

database engine to perform database management. The controls just do it in different ways. DAO is the most widespread approach to database management and, as such, has a very large installed base of applications. ADO is an emerging technology, which will one day supplant the DAO control. Be aware, as an emerging technology, ADO still has bugs! As we work through this course, we will identify some of these bugs and figure out how to work around them.

• Why Use DAO Instead of ADO?

⇒ You are modifying an existing application that uses DAO. ⇒ You are developing a small desktop application. ⇒ For now, the DAO control offers better database security features. ⇒ Microsoft Access uses DAO, so the market will be there for a while.

• Why Use ADO Instead of DAO?

⇒ You are beginning a new project, with potential for Internet deployment. ⇒ ADO is easier to use than DAO. ⇒ ADO is a more powerful control, allowing access to more data sources. ⇒ If you don’t use the Jet engine, ADO is the only way to go. ⇒ ADO will eventually become the only data control, with DAO becoming

obsolete. • In this course, we will discuss the use of both controls. Obviously, only Visual

Basic 6 users may use the material about the ADO data control. Visual Basic 5 users might like to look over the ADO material to become familiar with its use. In this particular chapter, we study the use of the DAO data control. The next chapter covers essentially the same material, using the ADO data control.

Page 48: VB6 DB Manual

Visual Basic and Databases

© LAP II

xlviii

DAO Data Control • The DAO data control is selected from the Visual Basic toolbox window. It’s

icon looks like this:

• The DAO data control is the primary interface between a Visual Basic

application and a database. It can be used without writing any code at all! Or, it can be a central part of a complex database management system.

• The data control (or tool) can access databases created by other programs

besides Visual Basic (or Microsoft Access). Some other formats supported include dBase, FoxPro, and Paradox.

• The data control can perform the following tasks:

1. Connect to a database. 2. Open a specified database table. 3. Create a virtual table based on a database query. 4. Pass database fields to other Visual Basic tools, for display or editing.

Such tools are bound to the database, or data bound controls. 5. Add new records, delete records, or update records. 6. Trap any errors that may occur while accessing data. 7. Close the database.

• As a rule, you need one data control for every database table, or virtual table,

you need access to. One row of the table is accessible to each data control at any one time. This is referred to as the current record.

Page 49: VB6 DB Manual

Contents

© LAP II

xlix

DAO Data Control Properties • The DAO data control is connected to a database simply be setting a few

properties. Important properties of this data control are:

Align Determines where data control is displayed. Caption Phrase displayed on the data control. Connect Type of database. Default is Microsoft Access (or Jet). DatabaseName Returns or sets the name of the source database for the

data control. Must be a fully qualified path and file name. EditMode Read-only at run-time. Indicates current state of editing for

the current record. Exclusive Indicates whether the underlying database is opened for

single-user or multi-user access. ReadOnly Indicates whether the data can be edited or not. Recordset A set of records defined by a data control’s Connect,

DatabaseName, and RecordSource properties. Run-time only.

RecordsetType Indicates type of Recordset you want data control to create RecordSource Determines the table (or virtual table) the data control is

attached to. Visible Establishes whether the data control appears on the form

at run-time. • When a DAO data control is placed on a form, it appears with the assigned

caption and four arrow buttons:

The arrows are used to navigate through the table records (rows). As indicated, the buttons can be used to move to the beginning of the table, the end of the table, or from record to record. In most applications, the data control never appears on the form – its Visible property is almost always False. In this case, moving from record to record is handled programmatically, a topic discussed later in this chapter.

Move to first record (row) Move to last record (row)

Move to next record (row)Move to previous record (row)

Page 50: VB6 DB Manual

Visual Basic and Databases

© LAP II

l

• After placing a DAO data control on a form, set the DatabaseName property first. Simply click on the ellipsis in the property box and choose the database. Then, set the RecordSource property. Click on that property’s drop-down arrow and a list of valid tables will be presented. Choose the desired table (or type in a valid SQL statement - studied in Chapter 5). This establishes the Recordset object. By following these steps carefully, we avoid run-time errors associated with inability to find referenced data.

Recordset Object • The Recordset object is an important concept. When we set the

RecordSource property (either select a table from the database or form a virtual table via a query), the data control (using the Jet engine) retrieves the needed records and places them in the Recordset object for our use. We will see that this object has its own properties and methods for our use.

• There are three types of recordsets, established via the RecordsetType

property:

Table Representation of a native database table (not formed via a query). You can add, change, or delete records.

Dynaset The default type, a Dynaset is formed as the result of a database query. You can add, change, or delete records from the underlying table(s). This is the most flexible Recordset type.

Snapshot A static copy of records that cannot be updated. Used if you are just viewing or searching a database table.

• In summary, the relationship between the data control, its two primary

properties (DatabaseName and RecordSource), and the Recordset object is:

Page 51: VB6 DB Manual

Contents

© LAP II

li

Data Bound Controls • The DAO data control allows us to easily connect to a database and form a

Recordset. Yet, that control alone does not provide us with anyway to view the information in the database. To view the information, we use data bound controls that are special controls with properties established by database fields. A data bound control is needed for each field (column) in the Recordset (database table) you need to view. Most of the standard Visual Basic tools can be used as data bound controls.

• Standard data bound data controls are:

Label Can be used to provide display-only access to a specified text data field. Caption property is data bound.

Text Box Can be used to provide read/write access to a specified text data field. Probably, the most widely used data bound tool. Text property is data bound.

Check Box Used to provide read/write access to a Boolean field. Value property is data bound.

Picture Box Used to display a graphical image from a bitmap, icon, gif, jpeg, or metafile file. Provides read/write access to a image/binary data field. Picture property is data bound.

Image Box Used to display a graphical image from a bitmap, icon, gif, jpeg, or metafile file (uses fewer resources than a picture box). Provides read/write access to a image/binary data field. Picture property is data bound.

• There are also three ‘custom’ data bound controls, the bound combo box, the

bound list box, and the bound data grid tool. We will look at these later. Data Bound Control Properties • To establish the connection of the data bound control to a database, we use a

few properties:

DataChanged Indicates whether a value displayed in a bound control has changed.

DataField Specifies the name of a field in the table pointed to by the respective data control.

DataSource Specifies which data control the control is bound to (indirectly specifying the database table).

Page 52: VB6 DB Manual

Visual Basic and Databases

© LAP II

lii

• If the data in any data bound control is changed and the user moves to another record in the database, the database will automatically be updated with the new data (assuming it is not ReadOnly). Be aware of this - it is an extremely powerful feature of the data control, but also a potential source of problems.

• To make using bound controls easy, follow these steps (in order listed) in

placing the controls on a form:

1. Draw the bound control on the same form as the data control to which it will be bound.

2. Set the DataSource property. Click on the drop-down arrow to list the data controls on your form. Choose one.

3. Set the DataField property. Click on the drop-down arrow to list the fields associated with the selected data control records. Make your choice.

4. Set all other properties, as needed.

Again, by following these steps in order, we avoid potential data access errors. • The relationships between a data bound control (DataSource and DataField

properties) and the DAO data control (Recordset property) are:

Page 53: VB6 DB Manual

Contents

© LAP II

liii

Example 3-1

Accessing the Books Database In this example, we begin working with the books (BIBLIO.MDB) database discussed in Chapter 2. This database is shipped with Visual Basic and is usually installed in the Visual Basic main directory. Using Windows Explorer, find this file. Make a copy of the database and place it in a working directory (you decide on a name – we use c:\VBDB\Working) where you will build your applications. We do this to insure there is always a valid copy of BIBLIO.MDB on your computer. You will see that the power of the DAO control also opens up the possibility of doing damage to a database (we, of course, will try to minimize this possibility). So, we are just living by the adage, “Better safe, than sorry.” 1. After copying BIBLIO.MDB to your working directory, start a new application.

We’ll develop a form where we can look through the Titles table in the books database. Place a DAO data control, four label boxes, and four text boxes on the form.

2. Set the following properties for each control. For the data control and the four

text boxes, make sure you set the properties in the order given.

Form1: Name frmTitles BorderStyle 1-Fixed Single Caption Titles Database

Data1:

Name datTitles Caption Titles DatabaseName BIBLIO.MDB (select from your working directory, don’t

type) RecordSource Titles (select, don’t type) ReadOnly True (to protect us from ourselves, at the moment)

Label1:

Caption Title

Label2: Caption Year Published

Page 54: VB6 DB Manual

Visual Basic and Databases

© LAP II

liv

Label3: Caption ISBN

Label4:

Caption Publisher ID

Text1: Name txtTitle DataSource datTitles (select, don’t type) DataField Title (select, don’t type) Locked True MultiLine True Text [Blank]

Text2:

Name txtYearPublished DataSource datTitles (select, don’t type) DataField Year Published (select, don’t type) Locked True MultiLine True Text [Blank]

Text3:

Name txtISBN DataSource datTitles (select, don’t type) DataField ISBN (select, don’t type) Locked True MultiLine True Text [Blank]

Text4: Name txtPubID DataSource datTitles (select, don’t type) DataField PubID (select, don’t type) Locked True MultiLine True Text [Blank]

Page 55: VB6 DB Manual

Contents

© LAP II

lv

When done, the form will look something like this:

3. Save the application. Run the application. Cycle through the various titles using the data control. Did you notice something? You didn’t have to write one line of Visual Basic code! This indicates the power behind the data control and data bound controls.

There’s one last thing. If you load this example from the code accompanying the course, you will need to reset the data control’s DatabaseName property, pointing to the directory in which you have stored the books database on your computer. In fact, you will have to do this anytime you use the examples provided with the course.

Page 56: VB6 DB Manual

Visual Basic and Databases

© LAP II

lvi

DAO Data Control Events • Like other controls, the DAO data control has events that are triggered at

various times during database access. In these events, we write BASIC code to perform specific needed tasks. In this chapter, we will not be using these event procedures, but we will define them to make our definition of the data control complete.

• Important DAO data control events:

Error Triggered when a data access error occurs and Visual Basic code is not being executed.

Reposition Triggered after data control pointer moves to a new record. Use to update information from non-data bound controls.

Validate Event triggered when the pointer is about to move away from the current record. This event can be used to cancel an update of a record or a move to a new record.

• These events will be discussed further when we begin development of

database management techniques in a later chapter. DAO Data Control Methods • To complete our definition of the DAO data control, we present some important

methods. These methods perform certain actions on the data control:

Refresh Requeries the database based on contents of the RecordSource property.

UpdateControls Restores the value of bound controls to original values (if no update has been performed).

UpdateRecord Saves the values of bound controls to the database without triggering the data control Validate event.

• Like events, DAO data control methods will be discussed further when we

begin development of database management techniques in a later chapter.

Page 57: VB6 DB Manual

Contents

© LAP II

lvii

DAO Data Control Recordset Properties • The Recordset object of the data control has its own set of properties. These

properties can only be accessed at run-time. To refer to a Recordset property, use a ‘double-dot’ notation. For example, if you have a data control named datExample, to refer to a property named PropertyName, the notation is:

datExample.Recordset.PropertyName

• Important data control Recordset properties are:

AbsolutePosition Long integer that either gets or sets the position of the current record.

BOF Returns True when the current record is positioned before any data.

Bookmark Sets or returns a bookmark to the current record. Used as a place marker in database management tasks.

EditMode Indicates the state of editing for the current record. EOF Returns True when the current record is positioned past

any data. PercentPosition Single data type that sets or gets the position of the

current record as a percentage of total records. Used for status indicators.

RecordCount The total number of records in the Recordset. Updatable Read-only at run-time. If True, records in the Recordset

can be modified. If False, records are read-only. • We will look at the BOF and EOF properties in the section on Recordset

Navigation. Other properties will be examined later in this course.

Page 58: VB6 DB Manual

Visual Basic and Databases

© LAP II

lviii

DAO Data Control Recordset Methods • The data control Recordset also has its own set of methods that perform

functions on the Recordset. These methods are invoked using the double-dot notation introduced for the Recordset properties. So, for a data control (datExample) and method (MethodName), you invoke the method via:

datExample.Recordset.MethodName

• Important Recordset methods are:

AddNew Adds a new record to the Recordset. All fields are set to null and this record becomes the current record.

CancelUpdate Used to cancel any pending updates (either with Edit or AddNew method)

Close Closes a Recordset. Delete The current record is deleted from the Recordset. Edit Places the current record in the Recordset into edit mode. MoveFirst Moves the current record pointer to the first record in the

Recordset. MoveLast Moves the current record pointer to the last record in the

Recordset. MoveNext Moves the current record pointer to the next record in the

Recordset. MovePrevious Moves the current record pointer to the previous record in

the Recordset. Requery Updates the data in a Recordset object by re-executing the

query on which the object is based. Update Saves the current contents of all data bound controls.

• We will look at the four ‘Move’ methods in the next section on Recordset Navigation. Other properties will be reviewed later in this course.

Page 59: VB6 DB Manual

Contents

© LAP II

lix

DAO Data Control Recordset Navigation • We have seen that, on the form, the DAO data control has four arrows that

allow the user to move to the first, next, previous, and last records in the recordset. Unfortunately, this control does not have a familiar look to a user and it may not be clear just exactly what functions the arrows perform. For this reason, we usually set the data control’s Visible property to False and provide a programmatic approach to moving from record to record, or recordset navigation.

• Four Recordset methods replicate the capabilities of the arrow buttons on the

data control: MoveFirst, MoveNext, MovePrevious, and MoveLast. For each function we need, a command button is added to the form, with a Click event procedure attached to the corresponding Recordset method.

• When programmatically navigating through the records, you need to be aware

of the position of the current record. For example, if you are at the first record and try a MovePrevious method, you will move past the beginning of the file. You can use the BOF property to see you are at the beginning of file and disallow such a move. You need a similar check at the end of a file to disallow an invalid MoveNext method.

Page 60: VB6 DB Manual

Visual Basic and Databases

© LAP II

lx

Quick Example 1 - Recordset Navigation 1. Load the project built in Example 3-1. Set the data control’s Visible property to

False. Add two command buttons with the following properties:

Command1: Name cmdPrevious Caption &Previous

Command2: Name cmdNext Caption &Next

The form should look like this (notice the data control is still there under the command buttons- it will only disappear at run-time).

2. Place this code in the cmdPrevious_Click event:

Private Sub cmdPrevious_Click() datTitles.Recordset.MovePrevious If datTitles.Recordset.BOF Then datTitles.Recordset.MoveFirst End If End Sub

Page 61: VB6 DB Manual

Contents

© LAP II

lxi

3. Place this code in the cmdNext_Click event:

Private Sub cmdNext_Click() datTitles.Recordset.MoveNext If datTitles.Recordset.EOF Then datTitles.Recordset.MoveLast End If End Sub

4. Save and run the application. Make sure the newly added buttons work as

they should. Try adding buttons to move to the first and last records. Can you write the code?

Page 62: VB6 DB Manual

Visual Basic and Databases

© LAP II

lxii

Summary • In this chapter, we finally used Visual Basic to connect to an actual database.

We learned there are two data controls available for database connection. The DAO data control (shipped with both Visual Basic 5 and Visual Basic 6) was discussed in this chapter. The same material is covered in the next chapter using the new ADO data control (Visual Basic 6 only).

• The DAO data control made connecting to a database a simple process. Only

a few properties (DatabaseName and RecordSource) needed to be set at design-time to form the Recordset for viewing.

• Data bound controls were seen to be our ‘window’ into the fields representing

the data control Recordset. Controls are bound by setting two properties: DataSource and DataField. Yet, even after all this work, all we can do right now is view databases, which in some applications is sufficient (think of your local library - they certainly don’t want patrons changing information in their database). To build a complete database management system, we need to know SQL, the powerful language behind database queries. This is discussed following a look at the ADO data control.

• If you’re feeling overwhelmed by all the material presented herein, don’t worry -

you’ll see it many more times as you continue through this course and become a more proficient database programmer.

Page 63: VB6 DB Manual

Contents

© LAP II

lxiii

Exercise 3

Northwind Traders Database A second sample database is included with Visual Basic 5 and Visual Basic 6. It is a database (NWIND.MDB) used by a fictional company (Northwind Traders) to handle its commerce. It has eight tables. In this exercise, we repeat the tasks of Example 3-1, using one table (Customers) in this database. This and the next exercise give you further practice in using the DAO data control and data bound controls and allows you to study the structure of another database. In working with databases, more examples to study help make you a better database programmer. 1. Copy NWIND.MDB to your working directory and start a new application. We’ll

develop a form where we can look through the Customers table in the Northwind Traders database. Place a DAO data control, four label boxes, and four text boxes on the form.

2. Set the following properties for each control. For the data control and the four

text boxes, make sure you set the properties in the order given.

Form1: Name frmCustomers BorderStyle 1-Fixed Single Caption Customers Database

Data1:

Name datCustomers Caption Customers DatabaseName NWIND.MDB (select from your working directory, don’t

type) RecordSource Customers (select, don’t type) ReadOnly True (to protect us from ourselves, at the moment)

Label1:

Caption Customer ID

Label2: Caption Company Name

Label3:

Caption Contact Name

Page 64: VB6 DB Manual

Visual Basic and Databases

© LAP II

lxiv

Label4: Caption Contact Title

Text1:

Name txtCustomerID DataSource datCustomers (select, don’t type) DataField CustomerID (select, don’t type) Locked True MultiLine True Text [Blank]

Text2:

Name txtCompanyName DataSource datCustomers (select, don’t type) DataField CompanyName (select, don’t type) Locked True MultiLine True Text [Blank]

Text3:

Name txtContactName DataSource datCustomers (select, don’t type) DataField ContactName (select, don’t type) Locked True MultiLine True Text [Blank]

Text4:

Name txtContactID DataSource datCustomers (select, don’t type) DataField ContactTitle (select, don’t type) Locked True MultiLine True Text [Blank]

Page 65: VB6 DB Manual

Contents

© LAP II

lxv

When done, the form will look something like this:

3. Save the application. Run the application. Cycle through the various customers using the data control.

Page 66: VB6 DB Manual

Visual Basic and Databases

© LAP II

lxvi

Visual Basic and Databases

4. Database Connection with ADO Technology Review and Preview • In the last chapter, we discussed the differences between the legacy Visual

Basic data control, the DAO control, and the new control shipped with Visual Basic 6, the ADO control. And, we looked at how to use the DAO control to connect to a database and view desired recordsets.

• In this chapter, we cover much of the same material from the previous chapter,

however, here we use ADO technology, examining both the data control and data environment. This chapter is self-contained, meaning it assumes you have not necessarily read the chapter on the DAO control. (For those who have read the previous chapter, you will notice lots of repetition). In addition to using the ADO data control for database access, we present a powerful new technology associated with the ADO data control, the data environment. Be aware you can only complete this particular chapter if you are using Visual Basic 6 - ADO technology is not available with Visual Basic 5.

Page 67: VB6 DB Manual

Contents

© LAP II

lxvii

ADO Data Control • The ADO (ActiveX Data Object) data control is the primary interface between

a Visual Basic application and a database. It can be used without writing any code at all! Or, it can be a central part of a complex database management system. The ADO data control does not appear in the standard Visual Basic toolbox - it must be added. Select Project from the main menu, then click Components. The Components window will appear. Select Microsoft ADO Data Control, then click OK. The control will be added to your toolbox. Its icon appears as:

• The data control (or tool) can access databases created by other programs

besides Visual Basic (or Microsoft Access). Some other formats supported include dBase, FoxPro, and Paradox.

• The data control can perform the following tasks:

1. Connect to a database. 2. Open a specified database table. 3. Create a virtual table based on a database query. 4. Pass database fields to other Visual Basic tools, for display or editing.

Such tools are bound to the database, or data bound controls. 5. Add new records, delete records, or update records. 6. Trap any errors that may occur while accessing data. 7. Close the database.

• As a rule, you need one data control for every database table, or virtual table,

you need access to. One row of the table is accessible to each data control at any one time. This is referred to as the current record.

Page 68: VB6 DB Manual

Visual Basic and Databases

© LAP II

lxviii

ADO Data Control Properties • The ADO data control is connected to a database simply be setting a few

properties. Important properties of this data control are:

Align Determines where data control is displayed. Caption Phrase displayed on the data control. CommandType Establishes source of Recordset (table or query). ConnectionString Contains the information used to establish a connection to

a database. EditMode Read-only at run-time. Indicates current state of editing for

the current record. LockType Indicates the type of locks placed on records during editing

(default setting makes databases read-only). Recordset A set of records defined by a data control’s

ConnectionString and RecordSource properties. Run-time only.

RecordSource Determines the table (or virtual table) the data control is attached to.

Visible Establishes whether the data control appears on the form at run-time.

• When an ADO data control is placed on a form, it appears with the assigned

caption and four arrow buttons:

The arrows are used to navigate through the table records (rows). As indicated, the buttons can be used to move to the beginning of the table, the end of the table, or from record to record. In most applications, the data control never appears on the form – its Visible property is almost always False. In this case, moving from record to record is handled programmatically, a topic discussed later in this chapter.

Move to first record (row) Move to last record (row)

Move to next record (row)Move to previous record (row)

Page 69: VB6 DB Manual

Contents

© LAP II

lxix

ConnectionString Property • After placing a data control on a form, you set the ConnectionString property.

The ADO data control can connect to a variety of database types. There are three ways to connect to a database: using a data link, using an ODBC data source, or using a connection string. We will look at connection to a Microsoft Access database using a connection string.

• Visual Basic can build the connection string for us. This process is best

illustrated by example. We will use the books database (BIBLIO.MDB) discussed in Chapter 2. This database is shipped with Visual Basic and is usually installed in the Visual Basic main directory. Using Windows Explorer, find this file. Make a copy of the database and place it in a working directory (you decide on a name – we use c:\VBDB\Working) where you will build your applications. We do this to insure there is always a valid copy of BIBLIO.MDB on your computer. You will see that the power of the ADO control also opens up the possibility of doing damage to a database (we, of course, will try to minimize this possibility). So, we are just living by the adage, “Better safe, than sorry.”

• Now, the steps to create our example connection string are:

1. Start a new Visual Basic project and place an ADO Data Control on the form.

2. Go to the Properties Window, click on the Connection String. Click on the ellipsis that appears. The Property Pages window appears.

3. Choose Use Connection String and click the Build button. The Data Link Properties window appears.

4. Choose the Provider tab and select Microsoft Jet 3.51 OLE DB Provider (an Access database).

5. Click the Next button to go to the Connection tab. 6. Click the ellipsis and use the Select Access Database dialog box to

choose the BIBLIO.MDB file in your working directory. Click Open. 7. Click Test Connection. Then, click OK (assuming it passed). Click OK in

the Property Pages window. The connection string is built and assigned to the ConnectionString property of the data control.

Page 70: VB6 DB Manual

Visual Basic and Databases

© LAP II

lxx

Recordset Object • The Recordset object is an important concept. When we set the

RecordSource property (either select a table from the database or form a virtual table via a query), the data control (using the Jet engine) retrieves the needed records and places them in the Recordset object for our use. We will see that this object has its own properties and methods for our use.

• In this chapter, the Recordset will be one of the native tables in the database.

Continuing with the BIBLIO.MDB example, let’s connect to the Titles table:

1. Go to the Properties window for the data control. Select 2-adCmdTable for the CommandType property for the data control (this tells the data control we will be using a native table). Now, click the RecordSource property. Click on the ellipsis that appears. The Property Pages window appears.

2. Click the drop-down button under Tables or Stored Procedure Name. Choose Titles.

3. Click OK in the Property Pages window. The RecordSource property of the data control is set, establishing the Recordset as the Titles table of the books database.

• In summary, the relationship between the data control, its two primary

properties (Connection String and RecordSource), and the Recordset object is:

Page 71: VB6 DB Manual

Contents

© LAP II

lxxi

Data Bound Controls • The ADO data control allows us to easily connect to a database and form a

Recordset. Yet, that control alone does not provide us with any way to view the information in the database. To view the information, we use data bound controls that are special controls with properties established by database fields. A data bound control is needed for each field (column) in the Recordset (database table) you need to view. Most of the standard Visual Basic tools can be used as data bound controls.

• Standard data bound data controls are:

Label Can be used to provide display-only access to a specified text data field. Caption property is data bound.

Text Box Can be used to provide read/write access to a specified text data field. Probably, the most widely used data bound tool. Text property is data bound.

Check Box Used to provide read/write access to a Boolean field. Value property is data bound.

Picture Box Used to display a graphical image from a bitmap, icon, gif, jpeg, or metafile file. Provides read/write access to a image/binary data field. Picture property is data bound.

Image Box Used to display a graphical image from a bitmap, icon, gif, jpeg, or metafile file (uses fewer resources than a picture box). Provides read/write access to a image/binary data field. Picture property is data bound.

• There are also three ‘custom’ data bound controls, data bound versions of the

standard list box (DataList), the standard combo box (DataCombo), and the standard grid control (DataGrid). We will look at these later.

Data Bound Control Properties • To establish the connection of the data bound control to a database, we use a

few properties:

DataChanged Indicates whether a value displayed in a bound control has changed.

DataField Specifies the name of a field in the table pointed to by the respective data control.

DataSource Specifies which data control the control is bound to (indirectly specifying the database table).

Page 72: VB6 DB Manual

Visual Basic and Databases

© LAP II

lxxii

• If the data in any data bound control is changed and the user moves to another record in the database, the database will automatically be updated with the new data (assuming it is not ReadOnly). Be aware of this - it is an extremely powerful feature of the data control, but also a potential source of problems.

• To make using bound controls easy, follow these steps (in order listed) in

placing the controls on a form:

1. Draw the bound control on the same form as the data control to which it will be bound.

2. Set the DataSource property. Click on the drop-down arrow to list the data controls on your form. Choose one.

3. Set the DataField property. Click on the drop-down arrow to list the fields associated with the selected data control records. Make your choice.

4. Set all other properties, as needed.

Again, by following these steps in order, we avoid potential data access errors. • The relationships between a data bound control (DataSource and DataField

properties) and the ADO data control (Recordset property) are:

Page 73: VB6 DB Manual

Contents

© LAP II

lxxiii

Example 4-1

Accessing the Books Database If you haven’t made a working copy of the database file (BIBLIO.MDB) as explained earlier, please do so now. Note you may be able to skip a few steps in this example, if you’ve already set the ConnectionString and RecordSource properties to point to the Titles table. 1. After copying BIBLIO.MDB to your working directory, start a new application.

We’ll develop a form where we can look through the Titles table in the books database. Place an ADO data control, four label boxes, and four text boxes on the form.

2. Set the following properties for each control. For the data control and the four

text boxes, make sure you set the properties in the order given.

Form1: Name frmTitles BorderStyle 1-Fixed Single Caption Titles Database

Adodc1:

Name datTitles Caption Titles CommandType 2-adCmdTable ConnectionString Use the Build option to point to the BIBLIO.MDB

database RecordSource Titles (select from list, don’t type)

Label1:

Caption Title

Label2: Caption Year Published

Label3:

Caption ISBN

Label4: Caption Publisher ID

Page 74: VB6 DB Manual

Visual Basic and Databases

© LAP II

lxxiv

Text1: Name txtTitle DataSource datTitles (select, don’t type) DataField Title (select, don’t type) Locked True MultiLine True Text [Blank]

Text2:

Name txtYearPublished DataSource datTitles (select, don’t type) DataField Year Published (select, don’t type) Locked True MultiLine True Text [Blank]

Text3:

Name txtISBN DataSource datTitles (select, don’t type) DataField ISBN (select, don’t type) Locked True MultiLine True Text [Blank]

Text4:

Name txtPubID DataSource datTitles (select, don’t type) DataField PubID (select, don’t type) Locked True MultiLine True Text [Blank]

Page 75: VB6 DB Manual

Contents

© LAP II

lxxv

When done, the form will look something like this:

3. Save the application. Run the application. Cycle through the various titles using the data control. Did you notice something? You didn’t have to write one line of Visual Basic code! This indicates the power behind the data control and data bound controls.

There’s one last thing. If you load this example from the code accompanying the course, you will need to reset the data control’s ConnectionString property, pointing to the directory in which you have stored the Northwind Traders database on your computer. In fact, you will have to do this anytime you use the examples provided with the course.

Page 76: VB6 DB Manual

Visual Basic and Databases

© LAP II

lxxvi

ADO Data Control Events • Like other controls, the ADO data control has events that are triggered at

various times during database access. In these events, we write BASIC code to perform specific needed tasks. In this chapter, we will not be using these event procedures, but we will define them to make our definition of the data control complete.

• Important ADO data control events:

WillMove Triggers before record pointer is moved from one row to another.

MoveComplete Event triggered after record pointer has been moved from one row to another.

EndofRecordset Triggers when the record pointer is moved past the last record in the recordset.

WillChangeRecordset Triggers before a change is made to the recordset. Used to trap unwanted changes.

RecordsetChangeComplete Triggers after a change is made to recordset. WillChangeRecord Triggers before updates for the current row

are sent to the data source. RecordChangeComplete Triggers after updates for the current row are

sent to the data source. WillChangeField Triggers before the current field in the

recordset is updated. FieldChangeComplete Triggers after the current field in the

recordset has been updated. • These events will be discussed further when we begin development of

database management techniques in a later chapter.

Page 77: VB6 DB Manual

Contents

© LAP II

lxxvii

ADO Data Control Method • To complete our definition of the ADO data control, we present a single

method:

Refresh Requeries the database based on contents of the RecordSource property.

• Like events, this ADO data control method will be discussed further when we

begin development of database management techniques in a later chapter. ADO Data Control Recordset Properties • The Recordset object of the data control has its own set of properties. These

properties can only be accessed at run-time. To refer to a Recordset property, use a ‘double-dot’ notation. For example, if you have a data control named datExample, to refer to a property named PropertyName, the notation is:

datExample.Recordset.PropertyName

• Important data control Recordset properties are:

AbsolutePosition Long integer that either gets or sets the position of the current record.

BOF Returns True when the current record is positioned before any data.

Bookmark Sets or returns a bookmark to the current record. Used as a place marker in database management tasks.

EditMode Indicates the state of editing for the current record. EOF Returns True when the current record is positioned past

any data. RecordCount The total number of records in the Recordset.

• We will look at the BOF and EOF properties in the section on Recordset

Navigation. Other properties will be examined later in this course.

Page 78: VB6 DB Manual

Visual Basic and Databases

© LAP II

lxxviii

ADO Data Control Recordset Methods • The data control Recordset also has its own set of methods that perform

functions on the Recordset. These methods are invoked using the double-dot notation introduced for the Recordset properties. So, for a data control (datExample) and method (MethodName), you invoke the method via:

datExample.Recordset.MethodName

• Important Recordset methods are:

AddNew Adds a new record to the Recordset. All fields are set to null and this record becomes the current record.

CancelUpdate Used to cancel any pending updates (either while editing or using the AddNew method)

Close Closes a Recordset. Delete The current record is deleted from the Recordset. Move Moves the current record pointer a specified number of

records forward or backward. MoveFirst Moves the current record pointer to the first record in the

Recordset. MoveLast Moves the current record pointer to the last record in the

Recordset. MoveNext Moves the current record pointer to the next record in the

Recordset. MovePrevious Moves the current record pointer to the previous record in

the Recordset. Requery Updates the data in a Recordset object by re-executing the

query on which the object is based. Update Saves the current contents of all data bound controls.

• We will look at the four ‘Move’ methods in the next section on Recordset Navigation. Other properties will be reviewed later in this course.

Page 79: VB6 DB Manual

Contents

© LAP II

lxxix

ADO Data Control Recordset Navigation • We have seen that, on the form, the ADO data control has four arrows that

allow the user to move to the first, next, previous, and last records in the Recordset. Unfortunately, this control does not have a familiar look to a user and it may not be clear just exactly what functions the arrows perform. For this reason, we usually set the data control’s Visible property to False and provide a programmatic approach to moving from record to record, or Recordset navigation.

• Four Recordset methods replicate the capabilities of the arrow buttons on the

data control: MoveFirst, MoveNext, MovePrevious, and MoveLast. For each function we need, a command button is added to the form, with a Click event procedure attached to the corresponding Recordset method.

• When programmatically navigating through the records, you need to be aware

of the position of the current record. For example, if you are at the first record and try a MovePrevious method, you will move past the beginning of the file. You can use the BOF property to see you are at the beginning of file and disallow such a move. You need a similar check at the end of a file to disallow an invalid MoveNext method.

Page 80: VB6 DB Manual

Visual Basic and Databases

© LAP II

lxxx

Quick Example 1 - Recordset Navigation 1. Load the project built in Example 4-1. Set the ADO data control’s Visible

property to False. Add two command buttons with the following properties:

Command1: Name cmdPrevious Caption &Previous

Command2:

Name cmdNext Caption &Next

The form should look like this (notice the data control is still there under the command buttons- it will only disappear at run-time).

2. Place this code in the cmdPrevious_Click event:

Private Sub cmdPrevious_Click() datTitles.Recordset.MovePrevious If datTitles.Recordset.BOF Then datTitles.Recordset.MoveFirst End If End Sub

Page 81: VB6 DB Manual

Contents

© LAP II

lxxxi

3. Place this code in the cmdNext_Click event:

Private Sub cmdNext_Click() datTitles.Recordset.MoveNext If datTitles.Recordset.EOF Then datTitles.Recordset.MoveLast End If End Sub

4. Save and run the application. Make sure the newly added buttons work as

they should. Try adding buttons to move to the first and last records. Can you write the code?

Page 82: VB6 DB Manual

Visual Basic and Databases

© LAP II

lxxxii

DAO or ADO – What’s the Difference? • We asked this same question in Chapter 3 before we looked at both data

controls. Now that we’ve seen how the two controls are used for database connection, it’s fair to ask the question again.

• Use of the two controls is nearly identical – you can see that in the fact that the

two sets of notes are nearly identical. The primary difference between the two data controls is in the properties used to connect to a database. The DAO control connects to the database using the DatabaseName property while the ADO control uses the ConnectionString.

• To construct a Recordset, the DAO control uses the RecordSource property.

The ADO control requires setting two properties: RecordSource and CommandType.

• The ADO data control offers more event procedures than the DAO control to

allow more complete control over database management. • So, the question still may be – which control should you use? You should

understand the use of both data controls because you will see them both as you progress as a Visual Basic programmer. For simple projects, the DAO control is adequate. For more detailed projects and for all new projects, we would recommend the ADO data control. It is new technology and will receive the bulk of Microsoft’s support with future releases of Visual Basic. And, as seen in the next section, it has some hidden powers we have yet to see!

Page 83: VB6 DB Manual

Contents

© LAP II

lxxxiii

ADO Data Environment • One big advantage of the new ADO data control is that you don’t even need it

to work with databases! Yes, that’s right. A new technology has emerged – the ADO Data Environment. The Data Environment acts like multiple data controls you can access from anywhere in your application. You can connect to multiple databases and form multiple views of the data in those databases. Data bound controls can bind to any data view in the Data Environment.

• The Data Environment is a shareable and reusable connection file that can be

used in any Visual Basic project. It is added to your project just like a form (it has a single property of interest – Name). The Data Environment provides a greatly simplified programming environment used to connect to data sources. It provides ‘drag-and-drop’ functionality for building interfaces and developing database reports (discussed in a later class).

• The Data Environment has two primary objects: the Connection object

(specifies the database similar to the ConnectionString property of the ADO data control) and the Command object (specifies the Recordset like the RecordSource property of the ADO control).

• To see the versatility of the Data Environment, here is a diagram of one with

five different recordsets being generated from two different databases:

Page 84: VB6 DB Manual

Visual Basic and Databases

© LAP II

lxxxiv

Connection Object • The primary feature of the Data Environment is the Connection object. It

specifies the information needed to connect to a particular database. • The Connection object has several properties:

Attributes Needed connection string properties passed to the Connection object.

CommandTimeout Time in seconds the server will wait for a command to return a reply.

ConnectionSource String that describes the path to the data source connection.

ConnectionTimeout Time in seconds the server will wait for a connection to open on the destination server.

Don’t worry if some of these properties don’t make sense right now.

Command Object • The Data Environment Connection object specifies a database. The

Command object specifies a database table (either a native table or a virtual table formed using a database query).

• The Command object is very flexible and can be used for very advanced

database applications. For now, we will use it to form a Recordset for our use. Some Command object properties are:

CommandText Specifies table to display or gives valid database

query statement. CommandType Specifies whether object is connected to database

native table or virtual table formed using a query. ConnectionName Name of associated Connection object. LockType Controls how data in table may or may not be

changed. Set to Read Only by default. Must be changed if you need to edit data.

• Like most things with Visual Basic, the Data Environment and associated

Connection and Command objects are best illustrated via example.

Page 85: VB6 DB Manual

Contents

© LAP II

lxxxv

Quick Example 2 - Use of ADO Data Environment In this example, we will form a Connection object to the books database (BIBLIO.MDB) database and a Command object for the Titles table. This is the same table used in the example with the ADO data control. This should illustrate the differences between using the Data Environment and the ADO data control. 1. Start a new project. Add a Data Environment to your project. To do this,

either right-click the Project Explorer window and choose Add, then Data Environment. Or, choose Add Data Environment under the Project menu item. There’s a chance that Add Data Environment may not be one of the menu choices. If this is the case, the problem is easy to solve. Select Components under the Project menu item. In the window that appears, choose the Designers tab and check the boxes next to Data Environment and Data Report, then click OK. The Data Environment will now be available. Once selected, a Data Environment will appear in the Project Explorer window. The Data Environment window should also appear. If it doesn’t, double-click the Data Environment listing in the Project Explorer window. It should look like this:

2. Go to the Properties window and assign a Name of denBooks to

DataEnvironment1. Assign a Name of conBooks to Connection1.

Page 86: VB6 DB Manual

Visual Basic and Databases

© LAP II

lxxxvi

3. We’ll now establish the Connection object:

⇒ Right-click on conBooks and select Properties. A Data Link Properties window (identical to that used to set the ConnectionString with the data control) will appear.

⇒ Choose the Provider tab and select Microsoft Jet 3.51 OLE DB Provider (an Access database).

⇒ Click the Next button to go to the Connection tab. Click the ellipsis and use the Select Access Database dialog box to choose the BIBLIO.MDB file in your working directory. Click Open. Click Test Connection. Then, click OK (assuming it passed).

⇒ Click OK in the Data Link Properties window. 4. And now, we will establish the Command object:

⇒ In the Data Environment window, right-click on conBooks. A pop-up menu

will appear. Select Add Command. A Command object is added to the environment.

⇒ Right-click Command1 and select Properties. A Properties window will appear. Make sure the General tab is active.

⇒ Give the Command object a name of comTitles. Make sure the Connection is conBooks (the Connection object you just created).

⇒ In the Source of Data, choose Database Object, then select Table. Finally, under Object Name, choose the Titles table from the drop-down list.

Page 87: VB6 DB Manual

Contents

© LAP II

lxxxvii

5. The Command object is complete. Right-click Titles and choose the Expand All option. All fields in the Titles table will be listed and the Data Environment window should look like this:

The Data Environment is now configured to allow access to the Titles table in the books database (BIBLIO.MDB) database. This configuration may have required more steps than simply using the ADO data control, but the steps are worth it. You’ll see that now where we attach some data bound controls to view the Titles table.

Page 88: VB6 DB Manual

Visual Basic and Databases

© LAP II

lxxxviiiData Bound Controls with the Data Environment • To establish the connection of a data bound control to a database using the

Data Environment, we use three properties:

DataField Specifies the name of a field in the table established by the Command object.

DataMember Specifies the Command object establishing the database table.

DataSource Specifies which Data Environment the control is bound to. Note there is one more property needed when compared to using the ADO data control - DataMember is not used with the data control.

• The relationships between a data bound control (DataSource, DataMember and DataField properties) and the Data Environment are:

• To use bound controls with the Data Environment, we could follow these steps

(in order listed) in placing the controls on a form:

1. Draw the bound control on the a form. 2. Set the DataSource property. Click on the drop-down arrow to list the Data

Environments in your project. Choose one. 3. Set the DataMember property. Click on the drop-down arrow to list the

Command objects in the selected Data Environment. Choose one. 4. Set the DataField property. Click on the drop-down arrow to list the fields

associated with the selected DataMember. Make your choice. 5. Set all other properties, as needed.

• The steps above are just one way to connect data bound controls to the Data

Environment. But, now let’s look at one of the powerful features of the Data Environment - ‘drag and drop’ data bound controls.

Page 89: VB6 DB Manual

Contents

© LAP II

lxxxix

Example 4-2

Drag and Drop Controls In this example, we will build the same interface used with the ADO data control in Example 4-1 using the drag and drop capabilities of the Data Environment. 1. Return to the previous example (Quick Example 2) where we set up the Data

Environment for the Titles table of the books database. Set up the Visual Basic environment so the Data Environment window and the Project window with an empty Form appears on the screen. Your screen should look something like this:

2. Set the following properties for the form:

Name frmDataEnvironment BorderStyle 1 - Fixed Single Caption Data Environment Example

Page 90: VB6 DB Manual

Visual Basic and Databases

© LAP II

xc

3. Left-click on the Title field in the Data Environment window and drag it to the Form. When the field is over the Form an icon will appear. This icon holds a label identifying the field and a text box for displaying the field. Release the mouse button when the icon is in the desired position. At this point, my form looks like this:

4. Go to the Properties window and look at the Name, DataField, DataMember,

and DataSource properties for the text box on the form:

Name txtTitle DataField Title DataMember comTitles DataSource denBooks

It’s magic! By dragging the Title field onto the form, the data bound control properties are automatically established by the Data Environment. This makes building an interface much easier. At this point, of course, you can change any properties regarding size and appearance.

5. Complete the interface by dragging the Year Published, ISBN, and PubID

fields onto the form. Move and resize any controls, as needed.

Page 91: VB6 DB Manual

Contents

© LAP II

xci

6. Save and run the application. Your screen should look something like this:

Note we have a problem. We can only view the first record in the database. The Data Environment provides no means for navigating between records. But, recall, we have looked at how to programmatically navigate between records when discussing the ADO data control. Those same methods can be used here.

Page 92: VB6 DB Manual

Visual Basic and Databases

© LAP II

xcii

Recordsets in the Data Environment • As configured, the Data Environment returns a Recordset that has properties

and methods identical to those of the ADO data control. A Recordset is returned for each Command object in the environment. Since there are many possible recordsets in one Data Environment, each is assigned a unique name by the environment, based on the Command object name. Make sure you give each Command object in a Data Environment a unique name.

• For a Command object named comExample, the Recordset is assigned the

name rscomExample (note the addition of the two letter prefix, rs). To read or set the property of this Recordset in a Data Environment named denExample, we use the double-dot notation of:

denExample.rscomExample.PropertyName

• Likewise to reference a method (such as one of the Move methods) for this

Recordset, we use the notation:

denExample.rscomExample.MethodName

Page 93: VB6 DB Manual

Contents

© LAP II

xciii

Quick Example 3 - Record Navigation with the Data Environment 1. Continue with Example 4-2 and add two command buttons with the following

properties:

Command1: Name cmdPrevious Caption &Previous

Command2:

Name cmdNext Caption &Next

2. The form should look like this:

3. Place this code in the cmdPrevious_Click event:

Private Sub cmdPrevious_Click() denBooks.rscomTitles.MovePrevious If denBooks.rscomTitles.BOF Then denBooks.rscomTitles.MoveFirst End If End Sub

Page 94: VB6 DB Manual

Visual Basic and Databases

© LAP II

xciv

4. Place this code in the cmdNext_Click event:

Private Sub cmdNext_Click() denBooks.rscomTitles.MoveNext If denBooks.rscomTitles.EOF Then denBooks.rscomTitles.MoveLast End If End Sub

5. Save and run the application. Make sure the newly added buttons work as

they should. Do you see how much easier it was to construct the form with the data bound controls, as compared to setting all the properties back in Example 4-1?

Page 95: VB6 DB Manual

Contents

© LAP II

xcv

DAO to ADO – ADO to DAO • What if you have a database application using the DAO data control that you

would like to update to the ADO data control or ADO data environment? Or, what if you need to adapt a Visual Basic 6 application using ADO to Visual Basic 5 and DAO? In this section, we offer a few tips for the conversions.

• Replacing one data control with another is simple if you pay attention to just a

couple of details. To switch from the DAO control to the ADO control, follow these steps:

⇒ Make note of the DAO control Name, DatabaseName, and RecordSource

properties. ⇒ Delete the DAO data control. ⇒ Add the ADO data control to the form. ⇒ Assign the new control the same Name property, insure the

ConnectionString is attached to the database specified by the DAO DatabaseName and use the same RecordSource property.

By following these steps, all data bound controls should still be properly connected. If not, it is a simple matter of re-establishing the DataSource and DataField properties for each control.

• Switching from the ADO control to the DAO control follows similar steps:

⇒ Make note of the ADO control Name, ConnectionString, and RecordSource properties.

⇒ Delete the ADO data control. ⇒ Add the DAO data control to the form. ⇒ Assign the new control the same Name property, set DatabaseName to the

database referenced in the ADO ConnectionString property, and use the same RecordSource property.

By following these steps, all data bound controls should still be properly connected. If not, it is a simple matter of re-establishing the DataSource and DataField properties for each control.

Page 96: VB6 DB Manual

Visual Basic and Databases

© LAP II

xcvi

• Updating from the DAO data control to the ADO data environment requires as a minimum:

⇒ Make note of the DAO control DatabaseName and RecordSource

properties. ⇒ Delete the DAO data control. ⇒ Add an ADO data environment to the project. ⇒ Configure the Connection object so it is attached to the database given by

DAO DatabaseName. ⇒ Configure a Command object such that it’s Source of Data is the same as

the DAO RecordSource property. ⇒ Modify data bound control properties – DataSource is bound to data

environment, DataMember is bound to Command object, DataField is bound to appropriate field (should be the same value used by DAO control).

• Moving from the ADO data environment to the DAO data control requires as

a minimum:

⇒ Make note of the database the ADO Connection object is connected to and the Source of Data for the Command object.

⇒ Delete the ADO data environment. ⇒ Add a DAO data control to the form. ⇒ Set the DatabaseName property such that it is connected to the same

database and set the RecordSource property to the same value used by the ADO Command object.

⇒ Modify data bound control properties – DataSource is bound to the DAO data control, DataMember is not used (blank it out), DataField is bound to appropriate field (should be the same value used by ADO data environment).

• All of the above conversions only address design mode setup. If you have

written any BASIC code that uses data control methods and properties or recordset methods and properties, you will have to make sure necessary modifications are made to insure your code works with the new data access technology.

Page 97: VB6 DB Manual

Contents

© LAP II

xcvii

Summary • In this chapter, we used the ADO data control to connect to and view a

database using data bound controls. The procedure was seen to be nearly identical to that of the DAO data control studied in the previous chapter.

• A new technology, the Data Environment, was also studied. The Data

Environment is a shareable and reusable connection file that can be used in any Visual Basic project. It is added to your project just like a form. The Data Environment provides a greatly simplified programming environment used to connect to data sources. It provides ‘drag-and-drop’ functionality for building interfaces.

• The ADO data control is still useful for quick prototyping of database

applications and we will occasionally use it for this purpose. But, for any serious application, we will forego the ADO data control in favor of the ADO Data Environment.

• At this point in the course, we have learned a lot, but still can only view a native

table in a database. In the next chapter, we learn the language that allows us to form any virtual view of data we wish. That language is SQL (structured query language), the heart of any database management system.

Page 98: VB6 DB Manual

Visual Basic and Databases

© LAP II

xcviii

Exercise 4-1

Northwind Traders Database A second sample database is included with Visual Basic 5 and Visual Basic 6. It is a database (NWIND.MDB) used by a fictional company (Northwind Traders) to handle its commerce. It has eight tables. In this exercise, we repeat the tasks of Example 4-1, using one table (Customers) in this database. This and the next exercise give you further practice in using the ADO data control and data bound controls and allows you to study the structure of another database. 1. Copy NWIND.MDB to your working directory and start a new application. We’ll

develop a form where we can look through the Customers table in the Northwind Traders database. Place an ADO data control, four label boxes, and four text boxes on the form.

2. Set the following properties for each control. For the data control and the four

text boxes, make sure you set the properties in the order given.

Form1: Name frmCustomers BorderStyle 1-Fixed Single Caption Customers Database

Adodc1:

Name datCustomers Caption Customers CommandType 2-adCmdTable ConnectionString Use the Build option to point to the NWIND.MDB

database RecordSource Customers (select from list, don’t type)

Label1:

Caption Customer ID

Label2: Caption Company Name

Label3:

Caption Contact Name

Label4: Caption Contact Title

Page 99: VB6 DB Manual

Contents

© LAP II

xcix

Text1: Name txtCustomerID DataSource datCustomers (select, don’t type) DataField CustomerID (select, don’t type) Locked True MultiLine True Text [Blank]

Text2:

Name txtCompanyName DataSource datCustomers (select, don’t type) DataField CompanyName (select, don’t type) Locked True MultiLine True Text [Blank]

Text3:

Name txtContactName DataSource datCustomers (select, don’t type) DataField ContactName (select, don’t type) Locked True MultiLine True Text [Blank]

Text4:

Name txtContactID DataSource datCustomers (select, don’t type) DataField ContactTitle (select, don’t type) Locked True MultiLine True Text [Blank]

Page 100: VB6 DB Manual

Visual Basic and Databases

© LAP II

c

When done, the form will look something like this:

3. Save the application. Run the application. Cycle through the various customers using the data control.

Page 101: VB6 DB Manual

Contents

© LAP II

ci

Exercise 4-2

Data Environment with Northwind Traders Database For more practice in connecting to databases, we repeat Example 4-3 and Quick Example 4, using the Northwind Traders database. In this exercise, we will first form a Connection object to the Northwind Traders (NWIND.MDB) database and a Command object for the Customers table. 1. Start a new project. Add a Data Environment to your project. Go to the

Properties window and assign a Name of denNorthwind to DataEnvironment1. Assign a Name of conNorthwind to Connection1. We’ll now establish the Connection object:

⇒ Right-click on conNorthwind and select Properties. A Data Link

Properties window (identical to that used to set the ConnectionString with the data control) will appear.

⇒ Choose the Provider tab and select Microsoft Jet 3.51 OLE DB Provider (an Access database).

⇒ Click the Next button to go to the Connection tab. Click the ellipsis and use the Select Access Database dialog box to choose the NWIND.MDB file in your working directory. Click Open. Click Test Connection. Then, click OK (assuming it passed).

⇒ Click OK in the Data Link Properties window. 2. And now, we will establish the Command object: In the Data Environment

window, right-click on comNorthwind. A pop-up menu will appear. Select Add Command. A Command object is added to the environment.

⇒ Right-click Command1 and select Properties. A Properties window will

appear. Make sure the General tab is active. ⇒ Give the Command object a name of Customers. Make sure the

Connection is conNorthwind (the Connection object you just created). ⇒ In the Source of Data, choose Database Object, then select Table.

Finally, under Object Name, choose the Customers table from the drop-down list.

Page 102: VB6 DB Manual

Visual Basic and Databases

© LAP II

cii

The Command object is complete. Right-click Customers and choose the Expand All option. All fields in the Customers table will be listed and the Data Environment window should look like this:

3. Set the following properties for the form:

Name frmDataEnvironment BorderStyle 1 - Fixed Single Caption Data Environment Example

4. Drag and drip the following fields from the Data Environment window to the

Form: CustomerID, CompanyName, ContactName, and ContactTitle. Add two command buttons with properties:

Command1:

Name cmdPrevious Caption &Previous

Command2:

Name cmdNext Caption &Next

Page 103: VB6 DB Manual

Contents

© LAP II

ciii

The form should look like this:

5. Place this code in the cmdPrevious_Click event:

Private Sub cmdPrevious_Click() denNorthwind.rscomCustomers.MovePrevious If denNorthwind.rscomCustomers.BOF Then denNorthwind.rscomCustomers.MoveFirst End If End Sub

6. Place this code in the cmdNext_Click event:

Private Sub cmdNext_Click() denNorthwind.rscomCustomers.MoveNext If denNorthwind.rscomCustomers.EOF Then denNorthwind.rscomCustomers.MoveLast End If End Sub

7. Save and run the application.

Page 104: VB6 DB Manual

Visual Basic and Databases

© LAP II

civ

Visual Basic and Databases

5. Database Queries with SQL Review and Preview • At this point in our study, we can view any table that is part of a database (a

native table). A powerful feature of any database management system is to have the ability to form any view of the data we desire. The formation of such virtual tables is discussed in this chapter.

• Virtual data views are obtained by querying the database. The language used

for such queries is the structured query language, or SQL. In this chapter, we will learn how to use SQL to extract desired information from a database. Note SQL is not just used with Visual Basic database applications. It is the standard language for database queries, hence all material learned here can be transferred to other database management systems.

Page 105: VB6 DB Manual

Contents

© LAP II

cv

SQL Background • SQL was developed at IBM in the early 1970’s, coincident with relational

database theory developed by E. F. Codd. SQL succeeded a previous database language called Sequel - hence, SQL is the “sequel to Sequel.” Because of this, many programmers pronounce SQL as “sequel.” The correct pronunciation is “ess-que-ell,” that is, just say the letters.

• SQL is a set of statements that tell a database engine (such as the Jet engine

with Visual Basic) what information the user wants displayed. The engine then processes that set of statements, as it sees fit, to provide the information. SQL statements fall into two categories: data manipulation language (DML) and data definition language (DDL). DDL statements can be used to define tables, indexes, and database relations. DML statements are used to select, sort, summarize, and make computations on data. We will only discuss DML statements.

• SQL has been adopted as an ANSI (American National Standards Institute)

standard. This means there is an established set of SQL statements that every database management system recognizes. Yet, even with this standard, each manufacturer has added its own ‘dialect’ to the standard. In these notes, we will use Microsoft Jet SQL. When a statement or function does not agree with the ANSI standard, this will be pointed out to the reader.

Page 106: VB6 DB Manual

Visual Basic and Databases

© LAP II

cvi

Basics of SQL • SQL can be used with any database management system, not just Visual

Basic. Hence, the syntax learned here will help any database programmer. SQL is a set of about 30 statements for database management tasks.

• To query a database, we form a SQL statement. A statement is a string of

SQL keywords and other information, such as database table and field names. This statement tells the database engine what information we want from the database. You do not have to tell the database engine how to get the information - it does all the hard work for you!

• What can a SQL statement accomplish?

⇒ Sort records ⇒ Choose fields ⇒ Choose records ⇒ Cross reference tables ⇒ Perform calculations ⇒ Provide data for database reports ⇒ Modify data

• Even though we don’t even know what a SQL statement looks like yet, we

need to set some rules on how to construct such statements. Then, we will look at how to use a SQL statement in a Visual Basic application.

• All SQL keywords in a SQL statement will be typed in upper case letters.

Even though SQL is ‘case-insensitive,’ this is good programming practice and allows us (and others) to differentiate between keywords and other information in a SQL statement.

• SQL uses the term row to refer to a database record and the term column to

refer to database field. This will not come into play in this class, but you should be aware of this difference if you read other books about SQL.

• String information imbedded within a SQL statement can be enclosed in

double-quotes (“) or single-quotes (‘). With Visual Basic, you should only use single-quotes to enclose imbedded strings. The reason for this is that the SQL statement is itself a string - so, in Visual Basic code, SQL statements must be enclosed in double-quotes. We enclose imbedded strings with single-quotes to avoid confusion.

Page 107: VB6 DB Manual

Contents

© LAP II

cvii

• SQL supports the use of wildcards in forming data views. The wildcard character for the Jet engine is an asterisk (*). Use of wildcards will be illustrated in many examples. ANSI Standard SQL implementations use the percent sign (%) as a wildcard.

• If a table or field name has an imbedded space, that name must be enclosed in

brackets ([]). For example, if the table name is My Big Table, in a SQL statement you would use:

[My Big Table]

This notation is not allowed in some SQL implementations. But in implementations that don’t recognize brackets, imbedded spaces in table and field names are not allowed, so it should never be a problem.

• To refer to a particular field in a particular table in a SQL statement, use a dot

notation:

TableName.FieldName

If either the table or field name has imbedded spaces, it must be enclosed in brackets.

• Now, we’re ready to start forming SQL statements and using them with Visual

Basic applications. One warning - SQL is a very powerful ally in obtaining and modifying data in a database. But, it can also be very destructive - a single SQL statement can wipe out an entire database! So, be careful and always provide safeguards against such potential destruction.

Page 108: VB6 DB Manual

Visual Basic and Databases

© LAP II

cviii

Where Does SQL Fit In Visual Basic? • Visual Basic uses SQL queries to define a data source. SQL statements are

processed by the Jet database engine (whether using DAO or ADO technology) to form a recordset object. This object contains the virtual database table formed as a result of the SQL statement. The resulting object can be used to display and, perhaps, update the database.

• How do we tell Visual Basic what the SQL statement is? It depends on

whether we want to provide the statement in design mode or run mode. In design mode, we simply set a property for the appropriate DAO or ADO control (or Data Environment). In run mode, how we process the SQL statement depends on the data access technology being used. This is addressed for each technology in the following sections.

• A result of interest from a SQL query is the number of records returned (if any).

With both DAO and ADO technology, the returned recordset has a RecordCount property. To receive a valid count with this property, however, the Jet database engine must ‘touch’ every record in the recordset. This is accomplished by performing a MoveLast method once the recordset is formed, followed immediately by a MoveFirst method. This accomplishes two tasks: provides a valid RecordCount and positions the record pointer at the top record. We will look at obtaining a valid RecordCount with the DAO and ADO technologies next.

• Note we say the database can perhaps be updated. How do we know if an

update can be performed? It all depends on the particular database access technology and SQL statement used to create the virtual table. This is discussed in later sections.

Page 109: VB6 DB Manual

Contents

© LAP II

cix

SQL with the DAO Data Control • When using the DAO (data access object) data control, the SQL statement

takes the place of the RecordSource property of the control. In design mode, simply go to the Properties Window for the data control, scroll down to the RecordSource property and type in a valid SQL statement. Many times, this will be a very long property. Obviously, it is assumed that the DatabaseName property of the data control has been set to the desired database file.

• In run mode, the SQL statement is also assigned to the RecordSource

property of the data control (Refresh the data control after assigning the RecordSource). For example, if we have a SQL statement named MySQL (this will be a string type variable) we want to use with a data control named datDAOExample (again, it is assumed that the DatabaseName property has been appropriately set), the BASIC code syntax is:

datDAOExample.RecordSource = MySQL datDAOExample.Refresh

We usually set the RecordSource property (and DatabaseName property, also) at run-time, rather than in design mode. Reasons for this are discussed in later chapters.

• Whether in design or run mode, a valid SQL statement will return a Recordset

object containing the selected database records. This object will have its own methods and properties for our use. In particular, to establish a valid RecordCount for the Recordset returned using a data control named datDAOExample, use these two lines of code:

datDAOExample.Recordset.MoveLast datDAOExample.Recordset.MoveFirst

Following these lines, the RecordCount is examined using:

datDAOExample.Recordset.RecordCount

Page 110: VB6 DB Manual

Visual Basic and Databases

© LAP II

cx

Quick Example 1 - SQL with the DAO Data Control 1. Start a new project. Add two label controls and a DAO data control. Set two

data control properties to:

DatabaseName BIBLIO.MDB (point to your working copy) RecordSource SELECT * FROM Titles

After setting the RecordSource property, the Properties Window should look like this:

Yes, this is your first SQL statement! You don’t have to recognize this right now, but it’s pretty easy to understand. The statement says SELECT all fields (the wildcard *) FROM the Titles table. This has the same result as choosing the Titles table as the RecordSource property.

2. Set the following two properties for the first label control (Label1):

DataSource Data1 DataField Title

Page 111: VB6 DB Manual

Contents

© LAP II

cxi

3. Place this code in the Form_Activate procedure (this counts and displays the number of records):

Private Sub Form_Activate() Data1.Recordset.MoveLast Data1.Recordset.MoveFirst Label2.Caption = Data1.Recordset.RecordCount End Sub

4. Save and run the application. You should see this (the first label control

showing a title and the second a number (the number of returned records):

Scroll through different titles using the data control arrows. 5. Now, add these two lines at the top of the Form_Activate procedure (these

lines set the RecordSource at run-time):

Data1.RecordSource = "SELECT * FROM Titles ORDER BY Title" Data1.Refresh

The SQL statement (enclosed in quotes since it is a BASIC string variable) is modified so the results are in alphabetical order.

6. Save and rerun the application. The ‘in code’ SQL statement should produce

the same records, but in order:

Page 112: VB6 DB Manual

Visual Basic and Databases

© LAP II

cxii

SQL with the ADO Data Control • When using the ADO (ActiveX data object) data control, the SQL statement

takes the place of the RecordSource property of the control. In design mode: ⇒ Establish the ConnectionString property. ⇒ Go to the Properties Window for the data control, scroll down to the

RecordSource property and click on the ellipsis that appears. The RecordSource Property Page will appear.

⇒ Under Command Type, select 1 - adCmdText (this tells the control we will be using a SQL statement). Then, in the Command Text (SQL) window, type in a valid SQL statement. When done, click OK.

• In run mode, the SQL statement is also assigned to the RecordSource

property of the data control (Refresh the data control after assigning the RecordSource). For example, if we have a SQL statement named MySQL (this will be a string type variable) we want to use with a data control named datADOExample (again, it is assumed that the ConnectionString property has been appropriately set), the BASIC code syntax is:

datADOExample.RecordSource = MySQL datADOExample.Refresh We usually set the RecordSource property (and ConnectionString property, also) at run-time, rather than in design mode. Reasons for this are discussed in later chapters.

• Whether in design or run mode, a valid SQL statement will return a Recordset

object containing the selected database records. This object will have its own methods and properties for our use. In particular, to establish a valid RecordCount for the Recordset returned using a data control named datADOExample, use these two lines of code:

datADOExample.Recordset.MoveLast datADOExample.Recordset.MoveFirst

Following these lines, the RecordCount is examined using:

datADOExample.Recordset.RecordCount

Page 113: VB6 DB Manual

Contents

© LAP II

cxiii

Quick Example 2 - SQL with the ADO Data Control 1. Start a new project. Add two label controls and an ADO data control. Build the

data control ConnectionString property to point to your working copy of BIBLIO.MDB.

2. Go to the Properties Window and click on the data control’s RecordSource

property. Click the ellipsis. The RecordSource Property Page will appear. Under Command Type, select 1 - adCmdText. Then, in the Command Text (SQL) window, type:

SELECT * FROM Titles

You should see:

When done, click OK. 3. Set the following two properties for the first label control (Label1):

DataSource Adodc1 DataField Title

Page 114: VB6 DB Manual

Visual Basic and Databases

© LAP II

cxiv

4. Place this code in the Form_Activate procedure (this counts and displays the number of records):

Private Sub Form_Activate() Adodc1.Recordset.MoveLast Adodc1.Recordset.MoveFirst Label2.Caption = Adodc1.Recordset.RecordCount End Sub

5. Save and run the application. You should see something like this (the first

label control showing a title and the second a number (the number of returned records):

Scroll through different titles using the data control arrows. 6. Add these two lines at the top of the Form_Activate procedure (these lines set

the RecordSource at run-time) to modify the SQL statement:

Data1.RecordSource = "SELECT * FROM Titles ORDER BY Title" Data1.Refresh

7. Save and rerun the application. The ‘in code’ SQL statement should produce

the same records, but in order:

Page 115: VB6 DB Manual

Contents

© LAP II

cxv

SQL with the ADO Data Environment • When using the ADO (ActiveX data object) data environment, the SQL

statement forms a new Command object within an existing Connection object. In design mode: ⇒ Establish the Connection object (connect to a database). ⇒ Right-click on the Connection object in the Data Environment window and

select Add Command. A new Command object will appear. ⇒ Right click the Command object and select Properties. The Properties

window appears - make sure the General tab is selected. Under Source of Data, click SQL Statement. The SQL window will become enabled. Type a valid SQL statement, then click OK.

(In all these steps, it is assumed that proper conventions were followed in naming all objects.)

• With the ADO data environment, we follow a different approach when using

SQL statements in run mode. The recordset created based on design-time parameters is first closed (use the Close method). Then, we re-open the recordset using the Open method and the new SQL statement. For example, assume we have a data environment named denExample, a command object named comExample and a new SQL statement named MySQL (this will be a string type variable). Recall the recordset associated with comExample will be named rscomExample. The code to close the current recordset and re-open it with a new SQL statement is:

denExample.rscomExample.Close denExample.rscomExample.Open MySQL

We’re not done, though. One more step is needed.

Page 116: VB6 DB Manual

Visual Basic and Databases

© LAP II

cxvi

• After creating the new recordset, all data bound controls are left bound to the original recordset. Without manually rebinding (in code) the controls to the new recordset, you won’t see the new results. Microsoft, in their Knowledge Base Articles, claims this is an intended behavior. We believe it is a bug that will hopefully be addressed as ADO technology matures. To rebind the data bound controls to the ADO data environment, you need to reset each control’s DataSource property. The code to rebind a control named ExampleControl to a data environment named DataEnvironmentName is: Set ExampleControl.DataSource = DataEnvironmentName Note use of the Set statement. Set must be used when initializing a programming object, as we are here. We will look at some automated techniques for rebinding in a later chapter. You can see that working with the data environment is a little trickier. But, after you’ve used it a few times, you’ll begin to appreciate its great advantages.

• Whether in design or run mode, a valid SQL statement will return a recordset

object containing the selected database records. Recall, in our example above, the returned recordset is named rscomExample. This object will have its own methods and properties for our use. In particular, to establish a valid RecordCount for the recordset returned by a data environment named denExample, use these two lines of code:

denExample.rscomExample.MoveLast denExample.rscomExample.MoveFirst

Following these lines, the RecordCount is examined using:

denExample.rscomExample.RecordCount

Page 117: VB6 DB Manual

Contents

© LAP II

cxvii

Quick Example 3 - SQL with the ADO Data Environment 1. Start a new project. Add two label controls and two command buttons (needed

to allow navigation among records). Add a Data Environment in the Project Explorer window. Right-click Connection1 and set Properties so it points to your working copy of BIBLIO.MDB.

2. Right-click on Connection1 and select Add Command. A new Command

object will appear. Right click that object and select Properties. The Properties window appears - make sure the General tab is selected. Under Source of Data, click SQL Statement. The SQL window will become enabled. Type:

SELECT * FROM Titles

You should see:

When done, click OK.

Page 118: VB6 DB Manual

Visual Basic and Databases

© LAP II

cxviii

3. Set the following properties for the first label control and the two command buttons:

Label1:

DataSource DataEnvironment1 DataMember Command1 DataField Title

Command1:

Caption &Previous Command2:

Caption &Next 4. Place this code in the Form_Activate procedure (this counts and displays the

number of records):

Private Sub Form_Activate() DataEnvironment1.rsCommand1.MoveLast DataEnvironment1.rsCommand1.MoveFirst Label2.Caption = DataEnvironment1.rsCommand1.RecordCount End Sub

5. Add this code to the command button Click events to allow navigation:

Private Sub Command1_Click() DataEnvironment1.rsCommand1.MovePrevious If DataEnvironment1.rsCommand1.BOF Then DataEnvironment1.rsCommand1.MoveFirst End If End Sub Private Sub Command2_Click() DataEnvironment1.rsCommand1.MoveNext If DataEnvironment1.rsCommand1.EOF Then DataEnvironment1.rsCommand1.MoveLast End If End Sub

Page 119: VB6 DB Manual

Contents

© LAP II

cxix

6. Save and run the application. You should see something like this (the first label control showing a title and the second a number (the number of returned records – this may be a different value for you, depending on the current state of the BIBLIO.MDB database):

Navigate through the records, if you like. 7. Add these three lines at the top of the Form_Activate procedure (these lines

set the RecordSource at run-time):

DataEnvironment1.rsCommand1.Close DataEnvironment1.rsCommand1.Open "SELECT * FROM Titles ORDER BY Title" Set Label1.DataSource = DataEnvironment1 These lines close the old recordset, re-open it with the new SQL statement, and then rebind the label control to the data environment.

8. Save and rerun the application. You obtain the same records, but ordered:

Page 120: VB6 DB Manual

Visual Basic and Databases

© LAP II

cxx

Example 5-1

SQL Tester Well, now we know some of the rules and syntax of SQL statements and how to use them with Visual Basic, but we still don’t know what a SQL statement looks like (well, we saw one in the examples). We correct all that now and start learning more about SQL. To test SQL statements we form, we build this example which allows us to enter SQL statements and see the results of the formed database queries. In this example, we use the DAO data control so both Visual Basic 5 and Visual Basic 6 users can build the same example. You can choose to use the ADO control (or data environment) if you choose. 1. Start a new project. Add a DAO data control, a text box control, two label

controls, a command button, and a DBGrid control to the form. Wait, you say, what is a DBGrid Control and why isn’t it in the toolbox? It is a DAO data bound control we haven’t looked at yet, but it is very powerful. The DBGrid control allows us to view and edit an entire database table by setting just one property (DataSource). It is a custom control that must be added to the toolbox. To do this, select Components under the Project menu item. In the window that appears, check the box next to Microsoft Data Bound Grid Control, then click OK. It is then available for selection from the toolbox. We will look further at this control in Chapter 6. Resize and position the controls so your form looks something like this:

Page 121: VB6 DB Manual

Contents

© LAP II

cxxi

A Brief (Hopefully) Interlude for Visual Basic 6 Users When you selected the Components tab, the choice for the Microsoft Data Bound Grid Control may not have been there. You will see a choice for Microsoft DataGrid Control. This is not the same control – this is the version of the control that works with ADO technology. So what can you do? There are two solutions: a quick one and a ‘not-so-quick’ one. We recommend the latter. Solution 1 – The Quick Solution: Use the ADO DataGrid control (make sure it has been added to the toolbox) in place of the DAO data bound grid control. You will also have to replace the DAO data control with the ADO data control. Use the same properties for the grid control and the data control with one exception. Recall the ADO data control does not have a DatabaseName property. If using the ADO control, set the ConnectionString property such that it points to your working copy of the BIBLIO.MDB database. No code changes are necessary – the code that works for the DAO data control will work for the ADO data control. When you attempt setting the DataSource property for the grid control, you will get this error message:

This is acceptable since we will be setting the data control’s RecordSource at run-time. You may also get this error when running the application. If so, just click OK. For your reference, we have built an ADO version of the SQL Tester program and included it with the example files (look for the project file with the AD suffix, Example5-1AD).

Page 122: VB6 DB Manual

Visual Basic and Databases

© LAP II

cxxii

Solution 2 – The ‘Not-So-Quick’ Solution: Here, we will install the desired DAO data grid control (and other DAO-based controls, if desired) onto your computer. The steps are many, but the effort is worth it, especially if you ever plan to use or build applications that employ DAO database technology. The information provided here was taken from Microsoft’s website. You will need your installation CD for Visual Basic 6. You will also have to be familiar with issuing DOS command line statements. Ask for help from someone if this is unfamiliar. Look in the \COMMON\TOOLS\VB\CONTROLS directory on the VB6 CD. This directory contains controls that shipped with Visual Basic 4/5 Professional and Enterprise Editions, which are no longer shipping with Visual Basic 6: AniBtn32.ocx, Gauge32.ocx, Grid32.ocx (the file we are interested in here), KeySta32.ocx, MSOutl32.ocx, Spin32.ocx, Threed32.ocx, MSChart.ocx To install these files on your computer, follow these steps: 1. Copy all of the files in this directory to your \WINDOWS\SYSTEM directory. 2. Register the controls by either Browsing to them in Visual Basic itself (select

the Browse option when selecting Components), or manually register them using RegSvr32.Exe. RegSvr32.EXE can be found in the \COMMON\TOOLS\VB\REGUTILS directory. The DOS command line is:

regsvr32.exe grid32.ocx

3. Register the design time licenses for the controls. To do this, merge the

vbctrls.reg file found in the \COMMON\TOOLS\VB\CONTROLS directory into your registry. You can merge this file into your registry using RegEdit.Exe (Win95, Win98, WinMe, Win2000 or WinNT4) or RegEd32.Exe (WinNT3.51):

regedit vbctrls.reg (or other reg files associated with the controls)

The DAO files (including the DAO data grid control) should now appear in the Components listing when choosing controls to add to your toolbox. Now back to our example.

Page 123: VB6 DB Manual

Contents

© LAP II

cxxiii

Set properties for the form and controls:

Form1: Name frmSQLTester BorderStyle 1-Fixed Single Caption SQL Tester

Data1:

Name datSQLTester Caption SQL Tester DatabaseName BIBLIO.MDB (point to your working copy)

Label1: Caption Records Returned

Label2:

Name lblRecords Alignment 2-Center BackColor White BorderStyle 1-Fixed Single Caption 0 FontSize 12

Command1:

Name cmdTest Caption Test SQL Statement TabStop False

DBGrid1:

Name grdSQLTester DataSource datSQLTester TabStop False

Text1:

Name txtSQLTester MultiLine True ScrollBars 2-Vertical

Page 124: VB6 DB Manual

Visual Basic and Databases

© LAP II

cxxiv

When done, the form should look like this:

With this example, we will type SQL statements in the text box area, then click the Test SQL Statement button. The data grid will display the returned records, while the label control will display the number of records returned. We need some code to do all of this.

2. All the code goes in the cmdTest_Click event:

Private Sub cmdTest_Click() 'Enable error handling On Error GoTo SQLError 'Read SQL statement and establish Recordsource datSQLTester.RecordSource = txtSQLTester.Text datSQLTester.Refresh If datSQLTester.Recordset.RecordCount <> 0 Then datSQLTester.Recordset.MoveLast datSQLTester.Recordset.MoveFirst lblRecords.Caption = datSQLTester.Recordset.RecordCount Else lblRecords.Caption = "0" End If txtSQLTester.SetFocus Exit Sub 'If error occurs, report it in message box SQLError: MsgBox Error(Err.Number), vbExclamation + vbOKOnly, "SQL Error" Exit Sub End Sub

Page 125: VB6 DB Manual

Contents

© LAP II

cxxv

Let’s spend some time seeing what’s going on in this code. The first thing we do is turn on error trapping. Without it, if we make a small error in a SQL statement, the program will stop. With it, we get a message indicating our mistake and are allowed to continue. Following error control, the SQL statement (from txtSQLTester) is processed and the Recordset established. The records are then counted and displayed.

Be careful in typing SQL statements. Although we have error trapping in SQL Tester, if you make a mistake, the returned error messages are (many times) not of much help. If you get an error, the best thing to do is retype the SQL command, paying attention to spacing, spelling, and proper punctuation.

3. Save the application and run it. Type the only SQL statement you know at this

time in the text box (SELECT * FROM Titles). Click Test SQL Statement and you should see:

Note the DB grid control display the entire table. You can scroll through the table or edit any values you choose. Any changes are automatically reflected in the underlying database. Column widths can be changed at run-time. Multiple row and column selections are possible. As we said, it’s a very powerful tool. Please note Records Returned values for your results may be different, depending on the current data in the database. Change the word SELECT to SLECT to make sure the error trapping works. Now, let’s use this SQL Tester to examine many kinds of SQL statements. When typing the statements, use upper case letters for the SQL keywords. Statements do not necessarily have be on a single line - multiple line SQL statements are fine and usually make them easier to read and understand.

Page 126: VB6 DB Manual

Visual Basic and Databases

© LAP II

cxxvi

SELECT/FROM SQL Statement • The most commonly used SQL statement is the one we’ve been using as an

example: the SELECT/FROM statement. This statement allows you to pick fields from one or more tables.

• The syntax for a SELECT/FROM SQL statement is:

SELECT [Fields] FROM [Tables] where [Fields] is a list of the fields desired and [Tables] is a list of the tables where the fields are to be found. The wildcard character (*) can be used for the fields list to select all fields from the listed table(s). For example, the statement we have been using:

SELECT * FROM Titles

selects and returns all fields from the BIBLIO.MDB database Titles table. Look at all fields in the other tables (Authors, Publishers, Title Author) using similar statements. When looking at the Title Author table, you need to write: SELECT * FROM [Title Author] Recall field and table names with imbedded spaces must be enclosed in brackets. Looking at each table will reacquaint you with the structure of the BIBLIO.MDB database tables and fields. We will use a lot in the rest of this chapter.

• If we only want selected fields from a table, we use a field list, which is a

comma-delimited list of the fields desired, or:

SELECT Field1, Field2, Field3 FROM Table

will return three named fields from Table. Make sure you do not put a comma after the last field name. To obtain just the Title and Year Published (name must be enclosed in brackets because of imbedded space) fields from the books database Titles table, use:

SELECT Title,[Year Published] FROM Titles

Note the field names are not written using the prescribed dot notation of Table.Field. The table name omission is acceptable here because there is no confusion as to where the fields are coming from. When using multiple tables, we must use the dot notation.

Page 127: VB6 DB Manual

Contents

© LAP II

cxxvii

Try this with the SQL tester and you will see just two fields are returned.

• The DISTINCT keyword can be used with SELECT to restrict the returned

records to one per unique entry for the field. That is, there are no duplicate entries. As an example, first try this with the SQL tester:

SELECT PubID FROM Titles

Page 128: VB6 DB Manual

Visual Basic and Databases

© LAP II

cxxviii

Now, try:

SELECT DISTINCT PubID FROM Titles

You should see far fewer records are returned - only distinct publishers are returned.

ORDER BY Clause • When you use a SELECT/FROM statement, the records are returned in the

order they are found in the selected table(s). To sort the returned records in some other order, you use the ORDER BY clause. The syntax is:

SELECT [Fields] FROM [Tables] ORDER BY FieldSort

This statement selects the listed fields from the listed tables and sorts them by the field named FieldSort. By default, the ordering is in ascending order. If you want the sort to be in descending order, the FieldSort name is followed by the keyword DESC.

Page 129: VB6 DB Manual

Contents

© LAP II

cxxix

• Try this statement with the SQL Tester:

SELECT * FROM Titles ORDER BY PubID

All records in the Titles table will be returned in order of Publisher ID.

Try this and the order should be reversed:

SELECT * FROM Titles ORDER BY PubID DESC

Page 130: VB6 DB Manual

Visual Basic and Databases

© LAP II

cxxx

• You can use more than one field in the ORDER BY clause. SQL will create a recordset based on all requested orderings. Try this with SQL tester:

SELECT * FROM Titles ORDER BY PubID,Title

The returned records will be in order of the publishers, with each publisher’s titles in alphabetic order.

• If you want to restrict the number of records returned by a SQL statement that

orders the returned records, you can use the TOP keyword with SELECT. TOP n returns the first n records. TOP n PERCENT returns the first n percent of the returned records. If two or more records have the same order value, they are all returned. Use the SQL Tester and try:

SELECT TOP 20 * FROM Titles ORDER BY PubID,Title

Twenty books should be returned. Now, try:

SELECT TOP 20 PERCENT * FROM Titles ORDER BY PubID,Title

Far more books will be returned.

Page 131: VB6 DB Manual

Contents

© LAP II

cxxxi

WHERE Clause • One of the most useful aspects of the SELECT/FROM SQL statement is its

ability to limit the returned recordset via the WHERE clause. This clause specifies some criteria that must be met in forming the recordset. The syntax is:

SELECT [Fields] FROM [Tables] WHERE Criteria

• The WHERE clause limits the number of returned records by allowing you to

do logical checks on the value of any field(s). Operators used to perfom these checks include:

< Less than <= Less than or equal to > Greater than >= Greater than or equal to = Equal <> Not equal Other operators are: Between Within a specified range In Specify a list of values Like Wild card matching

The WHERE clause can limit information displayed from one table or combine information from one or more tables. First, let’s do some several single table examples using SQL Tester.

Page 132: VB6 DB Manual

Visual Basic and Databases

© LAP II

cxxxii

Single Table WHERE Clause • Say we want to see all fields in the BIBLIO.MDB Titles table for books

published after 1995. And, we want the returned records ordered by Title. The SQL statement to do this is (we’ll type each clause on a separate line to clearly indicate what is going on - multiple line SQL statements are acceptable and, many times, desirable):

SELECT * FROM Titles WHERE [Year Published] > 1995 ORDER BY Title

This is where the real power of SQL comes in. With this simple statement, the Jet database engine quickly finds the desired records and sorts them - all without any coding on our part!

• What if we want to know information about all the book publishers in the state

of Washington. Try this SQL statement with the BIBLIO.MDB Publishers table:

SELECT * FROM Publishers WHERE State = ‘WA’

Note we enclosed the state name abbreviation (a string) in single quotes, as discussed earlier in this chapter. Try this SQL statement with the SQL tester and you should find one lonely publisher (BetaV) in the state of Washington! Wonder where Microsoft is?

Page 133: VB6 DB Manual

Contents

© LAP II

cxxxiii

• The BETWEEN keyword allows us to search for a range of values. Want all books published between 1995 and 1998? Use this SQL statement:

SELECT * FROM Titles WHERE [Year Published] BETWEEN 1995 AND 1998

• The IN keyword lets us specify a comma-delimited list of desired values in the

returned recordset. Say, we want to know the publishers in New York, Massachusetts, and California. This SQL statement will do the trick:

SELECT * FROM Publishers WHERE State IN (‘NY’, ‘MA’, ‘CA’)

Page 134: VB6 DB Manual

Visual Basic and Databases

© LAP II

cxxxiv• The LIKE keyword allows us to use wildcards in the WHERE clause. This lets

us find similar fields. Recall, the Jet engine wildcard character is the asterisk (*). [If you built the SQL Tester using the ADO data control, you need to use % as a wildcard in the LIKE clause. The % is a SQL standard for wildcards.] To find all authors with a ‘g’ anywhere in the their name, try:

SELECT * FROM Authors WHERE Author LIKE ‘*g*’

• Multiple criteria are possible by using the logical operators AND and OR. For

example, to find all books in the Titles table published after 1993 with a title that starts with the letters Data, we would use the SQL statement:

SELECT * FROM Titles WHERE [Year Published] > 1993 AND Title LIKE 'Data*'

Page 135: VB6 DB Manual

Contents

© LAP II

cxxxv

Multiple Table WHERE Clause • So far, almost everything we’ve done in this course has involved looking at a

single native (built-in) table in a database. This has been valuable experience in helping us understand database design, learning how to use the Visual Basic database tools, and learning some simple SQL statements. Now, we begin looking at one of the biggest uses of database management systems - combining information from multiple tables within a database. SQL makes such combinations a simple task.

• We still use the same SELECT/FROM syntax, along with the WHERE and

ORDER BY clauses to form our new virtual tables:

SELECT [Fields] FROM [Tables] WHERE Criteria ORDER BY [Fields]

The only difference here is there’s more information in each SQL statement, resulting is some very long statements. The [Fields] list will have many fields, the [Tables] list will have multiple tables, and the Criteria will have several parts. The basic idea is to have the SQL statement specify what fields you want displayed (SELECT), what tables those fields are found in (FROM), how you want the tables to be combined (WHERE), and how you want them sorted (ORDER BY). Let’s try an example.

• Notice the Titles table does not list a book’s publisher, but just publisher

identification (PubID). What if we want to display a book’s title (Title field in Titles table) and publisher (Company Name in Publishers table) in the same recordset? Let’s build the SQL statement. First, the SELECT clause specifies the fields we want in our ‘virtual’ table:

SELECT Titles.Title,Publishers.[Company Name]

Note the use of dot notation to specify the desired fields. With multiple tables, this avoids any problems with naming ambiguities.

• The FROM clause names the tables holding these fields:

FROM Titles,Publishers

Page 136: VB6 DB Manual

Visual Basic and Databases

© LAP II

cxxxvi• The WHERE clause declares what criteria must be met in combining the two

tables. The usual selection is to match a primary key in one table with the corresponding foreign key in another table. Here, we want the publisher identification numbers from each table to match:

WHERE Titles.PubID = Publishers.PubID

Any records from the tables that do not match the WHERE criteria are not included in the returned recordset.

• Lastly, we declare how we want the resulting recordset to be sorted:

ORDER BY Titles.Title • The complete SQL statement is thus:

SELECT Titles.Title,Publishers.[Company Name] FROM Titles,Publishers WHERE Titles.PubID = Publishers.PubID ORDER BY Titles.Title Try this with the SQL tester.

• Are you amazed? You have just seen one of the real powers of using SQL

with the Jet database engine (or any database system, for that matter). We simply told the engine what we wanted (via the SQL statement) and it did all of the work for us - no coding needed! Let’s do some more examples.

Page 137: VB6 DB Manual

Contents

© LAP II

cxxxvii

• In the previous example, say you just want books published by Que Corporation. Modify the SQL statement to read (we added an AND clause):

SELECT Titles.Title,Publishers.[Company Name] FROM Titles,Publishers WHERE Titles.PubID = Publishers.PubID AND Publishers.[Company Name] = ‘QUE CORP’ ORDER BY Titles.Title

• What if we want to list a book’s title, publisher, and author, ordered by the

author names? This requires using all four tables in the BIBLIO.MDB database. Let’s build the SQL statement. We want three fields:

SELECT Authors.Author,Titles.Title,Publishers.[Company Name] As mentioned, to retrieve this information requires all four tables: FROM Authors,Titles,Publishers,[Title Author]

We still need the publisher identification numbers to match, but now also need to make sure book titles (via the ISBN field) and author identification numbers match. The corresponding WHERE clause is: WHERE Titles.ISBN = [Title Author].ISBN AND Authors.Au_ID = [Title Author].Au_ID AND Titles.PubID = Publishers.PubID

Page 138: VB6 DB Manual

Visual Basic and Databases

© LAP II

cxxxviii

Finally, the results are sorted: ORDER BY Authors.Author Putting all this in the SQL tester gives us over 16,000 listings (one entry for every author and every book he or she wrote or co-wrote):

Such power! Can you imagine trying to write BASIC code to perform this record retrieval task?

• If the displayed field name does not clearly describe the displayed information,

you can alias the name, or change it to something more meaningful using the AS clause. As a simple example, try this:

SELECT Au_ID AS [This Author] FROM Authors

Page 139: VB6 DB Manual

Contents

© LAP II

cxxxix

Notice the displayed column is now This Author.

The field name is unaffected by aliasing - only the displayed name changes. • Important - Database tables combined (forming a virtual data view) using DAO

technology and the SQL WHERE clause cannot be updated. The data can only be viewed. Go ahead - combine tables using a SQL statement with a WHERE clause and try to change a value in the resulting grid. You can’t do it! The ability to update a DAO recordset is established by the read-only Updatable property. Is this a problem? Not if you are just displaying information for a user. But, if you need editing capabilities with DAO, do not use the WHERE clause to join tables.

• Any recordset established using ADO technology (even with a combining

WHERE clause) can be updated, depending on locks placed on the recordset. The use of such locks is discussed in a later chapter.

• To provide editing in DAO recordset, you need to use the SQL JOIN clauses.

Using JOIN clauses will also work with ADO recordsets. Let’s take a look at such a clause.

Page 140: VB6 DB Manual

Visual Basic and Databases

© LAP II

cxl

INNER JOIN Clause • When combining tables, the SQL INNER JOIN clause does the same work as

the WHERE clause and it returns a recordset that can be updated (for both DAO and ADO technologies). The syntax for an INNER JOIN is a little different than that of the WHERE clause.

SELECT [Fields] FROM Table1 INNER JOIN Table2 ON Linking Criteria WHERE Criteria ORDER BY [Fields]

This rather long statement begins by specifying the fields to SELECT. The FROM clause specifies the fields will come from the first table (Table1) being INNER JOINed with a second table (Table2). The ON clause states the linking criteria (usually a matching of key values) to be used in the join. At this point, the tables are combined. You can still use a WHERE clause to extract specific information from this table (you just can’t use it to combine tables) and an ORDER BY clause, if desired. Let’s repeat the examples just done with the WHERE clause.

• To display a book title and publisher name, the SELECT clause is:

SELECT Titles.Title, Publishers.[Company Name] We want to ‘join’ the Titles table with the Publishers table, making sure the PubID fields match. The corresponding INNER JOIN statement is: FROM Titles INNER JOIN Publishers ON Titles.PubID = Publishers.PubID Lastly, we order by the Title: ORDER BY Titles.Title

Page 141: VB6 DB Manual

Contents

© LAP II

cxli

Try this SQL statement in the SQL tester and you should obtain the same results seen earlier with the WHERE clause:

• Try to change a value in the data grid for this example. You should see that,

as expected, use of the INNER JOIN provides an updatable recordset. If you leave your change as is, it will be written as a permanent modification to the database! So, we suggest ‘undoing’ your change. You have just learned one of your first skills in building a complete database management system - how to edit an existing database. It was easy, wasn’t it? This ease comes from the power of the Jet database engine. There are times we won’t want editing the database to be so easy. Limiting these capabilities are discussed in the next chapter on Visual Basic interfaces.

• To illustrate use of the WHERE clause (to limit displayed records) in

conjunction with the JOIN clause, try this modified SQL statement with SQL Tester:

SELECT Titles.Title, Publishers.[Company Name] FROM Titles INNER JOIN Publishers ON Titles.PubID = Publishers.PubID WHERE Publishers.[Company Name] = ‘QUE CORP’ ORDER BY Titles.Title Only QUE CORP publishers will be listed. And, the recordset can still be edited (WHERE only affects ‘updatability’ of DAO recordsets when used to combine information on tables).

Page 142: VB6 DB Manual

Visual Basic and Databases

© LAP II

cxlii

• Use of the INNER JOIN clause to combine information from more than two tables is a little more complicated. The tables need be joined in stages, nesting the INNER JOIN clauses using parentheses for grouping. Assume we have three tables (Table1, Table2, Table3) we want to combine. Table1 and Table3 have a common key field for linking (Key13), as do Table2 and Table3 (Key23). Let’s combine these three tables using INNER JOIN. In the first stage, we form a temporary table that is a result of joining Table2 and Table3 using Key23 for linking:

Table2 INNER JOIN Table3 ON Table2.Key23 = Table3.Key23 In the next stage, we join Table1 with this temporary table (enclose it in parentheses) using Key13 for linking: Table1 INNER JOIN (Table2 INNER JOIN Table3 ON Table2.Key23 = Table3.Key23) ON Table1.Key13 = Table3.Key13 This nested statement is used in the SQL statement to specify the tables for field selection. Notice we’ve spread this over a few lines to make it clearer - any SQL processor can handle multiple line statements. The multiple table INNER JOIN can be generalized to more tables - just pay attention to what tables link with each other. Always make sure the tables you are joining, whether a temporary joined table or a database table, have a common key.

• Remember the example we did earlier where we listed Author, Title, and

Publisher in the BIBLIO.MDB database? Let’s build that SQL statement. First, SELECT the fields:

SELECT Authors.Author,Titles.Title,Publishers.[Company Name] This is the same SELECT we used previously. Now, we need to form the FROM clause by combining four tables in three stages (one for each common key linking). In the first stage, combine the Publishers and Titles tables (PubID is common key): Publishers INNER JOIN Titles ON Publishers.PubID=Titles.PubID)

Page 143: VB6 DB Manual

Contents

© LAP II

cxliii

Now, join this temporary table (put its statement in parentheses) with the [Title Author] table (ISBN is common key): (Publishers INNER JOIN Titles ON Publishers.PubID=Titles.PubID) INNER JOIN [Title Author] ON Titles.ISBN=[Title Author].ISBN In the final stage, join the Authors table with this temporary table (enclose its statement in parentheses) using Au_ID as the key: Authors INNER JOIN ((Publishers INNER JOIN Titles ON Publishers.PubID=Titles.PubID) INNER JOIN [Title Author] ON Titles.ISBN=[Title Author].ISBN) ON Authors.Au_ID=[Title Author].Au_ID The FROM clause needed for the combined data view is now complete. The final line in the SQL statement orders the data: ORDER BY Authors.Author Whew! Try this full statement with the SQL tester and you should get the same results seen earlier using the WHERE clause. The difference, of course, is that the recordset here can be updated.

Page 144: VB6 DB Manual

Visual Basic and Databases

© LAP II

cxliv

OUTER JOIN Clause • The INNER JOIN only retrieves records that have a match on both sides of the

JOIN. For example, with BIBLIO.MDB, the INNER JOIN statement:

Publishers INNER JOIN Titles ON Publishers.PubID = Titles.PubID In this statement, if there is a PubID in the Publishers table without a corresponding PubID in the Titles table, that value will not be in the returned recordset. If you want all records returned, whether there is a match or not, you need to use what is called an OUTER JOIN. There are two forms for the OUTER JOIN.

• A RIGHT OUTER JOIN includes all records from the second-named table (the

right-most table), even if there are no matching values for records in the first-named (left-most table). Try this with SQL Tester:

SELECT Titles.Title, Publishers.[Company Name] FROM Titles RIGHT OUTER JOIN Publishers ON Titles.PubID = Publishers.PubID ORDER BY Titles.Title

There are several publishers (about 19 or so) without corresponding titles in the database.

Page 145: VB6 DB Manual

Contents

© LAP II

cxlv

• A LEFT OUTER JOIN includes all records from the first-named table (the left-most table), even if there are not matching values for records in the second-named (right-most table). Try this with SQL Tester:

SELECT Titles.Title, Publishers.[Company Name] FROM Titles LEFT OUTER JOIN Publishers ON Titles.PubID = Publishers.PubID ORDER BY Titles.Title

The returned recordset is identical to that obtained with the INNER JOIN. Obviously, all books in the database have a corresponding publisher - that’s actually a good thing.

Page 146: VB6 DB Manual

Visual Basic and Databases

© LAP II

cxlvi

Visual Basic Functions with SQL • The Jet database engine allows you to use any valid BASIC function as part of

a SQL statement. This lets you modify the displayed information. It does not affect the underlying information in the database. As an example, say you want all book titles in the BIBLIO.MDB Titles database to be listed in upper case letters. Try this SQL statement with SQL Tester:

SELECT UCase(Titles.Title) FROM Titles

Notice SQL assigns a heading of Expr1000 to this ‘derived’ field. We can use the alias feature of SQL change this heading to anything we want (except the name of an existing field). Try this: SELECT UCase(Titles.Title) AS Title FROM Titles

• Or, what if we had some process that could only use the 10 left-most

characters of the book title. This SQL statement will do the trick:

SELECT UCase(Titles.Title) AS Title FROM Titles

Page 147: VB6 DB Manual

Contents

© LAP II

cxlvii

• You can also do BASIC math in a SQL statement. The BIBLIO.MDB database Authors table has Year Born as a field. This SQL statement will display each author and their age in 1999 (when this is being written):

SELECT Authors.Author,(1999-Authors.[Year Born]) AS Age FROM Authors

Note that most of the listings do not have an Age value. The reason for this is because only a few of the author records have birth year entries - the entries are NULL (containing no information).

• NULL is a special value meaning there is nothing there - this is not the same

as an empty string or blank space. In our work, we will try to avoid placing NULLs in a database, but sometimes this is not possible or they may exist in other databases. You need to decide how to handle NULLs in your design. We will see examples where they cause problems. A NULL field can be tested using the SQL functions IS NULL and IS NOT NULL. We can add this to the SQL statement above to find just the Authors records with a birth year:

SELECT Authors.Author,(1999-Authors.[Year Born]) AS Age FROM Authors WHERE Authors.[Year Born] IS NOT NULL

You should now find 20 authors with ages listed.

Page 148: VB6 DB Manual

Visual Basic and Databases

© LAP II

cxlviii

SQL Aggregate Functions • In addition to BASIC functions, the Jet database engines supports the standard

SQL aggregate functions. These are functions that let you compute summary statistics for fields in your database, alias the results, and display them in a recordset. NULL fields are ignored by the aggregate functions.

• The aggregate functions and their results are:

AVG(Field) Average value of the field COUNT(Field) Number of entries for the field FIRST(Field) First value of the field LAST(Field) Last value of the field MAX(Field) Maximum value of the field MIN(Field) Minimum value of the field SUM(Field) Sum of the field values

• Try this example with the Authors table:

SELECT COUNT(Authors.Author) AS HowMany, AVG(Authors.[Year Born]) AS AveYear, FIRST(Authors.[Year Born]) AS FirstYear, LAST(Authors.[Year Born]) AS LastYear, MAX(Authors.[Year Born]) AS MaxYear, MIN(Authors.[Year Born]) AS MinYear, SUM(Authors.[Year Born]) AS SumYear FROM Authors

Page 149: VB6 DB Manual

Contents

© LAP II

cxlix

Note some of the aggregate fields (FIrstYear, LastYear) have no values since these are NULL fields.

• Aggregate functions can be used to group results. The GROUP BY clause lets

you determine records with duplicate field values. Want to know how many publishers in your database are in each state? Try this SQL statement:

SELECT Publishers.State, Count(Publishers.State) as HowMany FROM Publishers GROUP BY Publishers.State

• You can use the HAVING qualifier to further reduce the grouping obtained with

a GROUP BY clause. Say in the above example, you only want to display states starting with the letter M (a strange request, we know). This SQL state will do the trick (try it):

SELECT Publishers.State, Count(Publishers.State) as HowMany FROM Publishers GROUP BY Publishers.State HAVING Publishers.State LIKE ‘M*’

Page 150: VB6 DB Manual

Visual Basic and Databases

© LAP II

cl

SQL Construction Tools • We’ve completed our review of the SQL language. There are other commands

we haven’t looked at. If you would like to know more, there are numerous references available for both ANSI standard SQL and the Jet database engine version. You now know how to construct SQL statements to extract desired information from a multi-table database and you know how to read other’s SQL statements.

• You have seen that constructing SQL statements is, at times, a tedious

process. To aid in the construction of such statements, there are several tools available for our use. We’ll discuss two: one in Microsoft Access and one available with the ADO data environment.

• To build a SQL query using Microsoft Access, you obviously must have Access

installed on your computer. As an example, we will build the SQL query that displays Author, Title, and Publisher for each book in the BIBLIO.MDB:

⇒ Start Access and open your copy of the BIBLIO.MDB. Click the

Queries tab and select New. Select Design View, click OK. ⇒ Click the Tables tab. Add all four tables. When done, click Close.

A split window appears with the four linked tables at the top (showing the relationships between primary and foreign keys) and a table in the lower portion.

⇒ In the lower portion of the window, click the first Field column, click the drop-down arrow and select Authors.Author. Under Sort, choose Ascending (sorting by Author). In the second column, click the drop-down arrow and select Titles.Title. In the third column, click the drop-down arrow and select Publishers.Company Name. When done, you should see (I moved the tables around a bit):

Page 151: VB6 DB Manual

Contents

© LAP II

cli

⇒ Click the exclamation point (!) on the Access toolbar to build the recordset. Now, click View on the main Access menu and select SQL View.

• Like magic, the SQL statement that was used to develop the recordset is

displayed:

SELECT Authors.Author, Titles.Title, Publishers.[Company Name] FROM (Publishers INNER JOIN Titles ON Publishers.PubID = Titles.PubID) INNER JOIN (Authors INNER JOIN [Title Author] ON Authors.Au_ID = [Title Author].Au_ID) ON Titles.ISBN = [Title Author].ISBN ORDER BY Authors.Author;

Notice a couple of things about this query. First, it uses the INNER JOIN clause to combine tables. Hence, this query could be used with DAO (if you need an updatable recordset) or ADO. Second, notice the semicolon (;) at the end of the query. This is not needed and will be ignored by the Jet database engine. You could now cut and paste the above query wherever you need it in your Visual Basic application (setting a design time property or in your BASIC code). You may need to make some adjustments to the query to make sure it does not result in any syntax errors at run-time. Notice this generated query is very much like that developed earlier in these notes. It’s similar because the author used Access to generate that query - you, too, should use the Access query building capabilities whenever you can. You are assured of a correct SQL statement, helping to minimize your programming headaches.

• If you have Visual Basic 6 and are using the ADO data environment, you can also have your SQL queries built for you. Again, this process is best illustrated by example (review the steps explained in Chapter 4 to implement the ADO data environment). The steps are similar to those just used with Access (not unexpected since they probably use the same underlying code). Start a new project in Visual Basic 6.

⇒ Add a Data Environment to the project and set the Properties of the

Connection object so it is attached to your copy of the BIBLIO.MDB database.

⇒ Right-click the Connection object and choose Add Command. ⇒ Right-click the Command object and select Properties. A

Properties window will appear. Under Source of Data, choose SQL Statement, then click the SQL Builder button. A Data View window and Design Window (with several ‘panes’) appear.

Page 152: VB6 DB Manual

Visual Basic and Databases

© LAP II

clii

⇒ In the Data View window, expand Connection, then expand Tables. Drag (in order) these tables from the Data View window to the top pane of the Design Window: Publishers, Titles, Title Author, and Authors. You need to do them in this order to insure proper connection of keys. If any keys are not correctly connected, you can make manual connections by dragging a key in one table to the corresponding key in another table. At this stage, the Design Window should look like this (I’ve moved the tables around to show the links):

⇒ Click on the first row under Column. Click the drop-down arrow and select Authors.Author. Click the first row under Sort Type. Choose Ascending.

⇒ In the second row, choose Titles.Title. In the third row, choose Publishers.`Company Name`. In the third pane, you should see the SQL statement that was built for you (close out the Design Window and this statement will be seen in the Command object)

Page 153: VB6 DB Manual

Contents

© LAP II

cliii

• The SQL statement built with SQL Builder is this:

SELECT Authors.Author, Titles.Title, Publishers.`Company Name` FROM Publishers, Titles, `Title Author`, Authors WHERE Publishers.PubID = Titles.PubID AND Titles.ISBN = `Title Author`.ISBN AND `Title Author`.Au_ID = Authors.Au_ID ORDER BY Authors.Author

Notice SQL Builder uses WHERE to join tables, not INNER JOIN. Hence, if you use this statement with DAO, the resulting recordset will not be updatable. This makes sense – SQL builder only works with the ADO data environment, so the only way you’d get this statement into a DAO application is via cut and paste. And, if you’ve gone to that much trouble, we have to assume you know what you’re doing (i.e. the DAO recordset cannot be updated). Also, notice tables and fields with imbedded spaces are surrounded by apostrophes, not brackets. This is another way to enclose names with imbedded spaces and will be accepted by the Jet engine. The preferred method is still using brackets. Note these symbols are apostrophes (`), the symbol sharing the key with a tilde (~), not a single quote (‘), the symbol sharing the keyboard with a double-quote. Single quotes will cause errors – a good reason to use brackets instead – no potential for such hard to trace errors.

Page 154: VB6 DB Manual

Visual Basic and Databases

© LAP II

cliv

Building SQL Commands in Code • In each example in this chapter, we formed a SQL command and processed it

to obtained a returned recordset (our virtual data view). What do you do if you don’t know the SQL command prior to implementing it as a Visual Basic property (either at design-time or run-time)? For example, the user of the books database may want to know all the publishers in Chicago. Or, the user may want to search the database for all authors whose name starts with a G.

• In both of the above examples, we have no idea what the user will select. We

need to provide the user a method to make a selection then, once the selection is made, build the SQL statement in Visual Basic. Fortunately, the BASIC language (used in all procedures) is rich with string handling functions and building such statements in code is a relatively straightforward process.

• To build a SQL command in code, form all the known clauses as string

variables. Once the user makes the selections forming the unknown information, using string concatenation operators (& or +) to place these selections in their proper position in the complete SQL statement. That statement can then be processed at run-time, using one of the methods discussed earlier in this chapter. The final example in this chapter demonstrates this technique.

Page 155: VB6 DB Manual

Contents

© LAP II

clv

Example 5-2

Searching the Books Database We build an application (using the BIBLIO.MDB books database) that displays a book’s author, title, and publisher (none of which are updateable). The user may display all books in the database or, alternately, search the database for books by particular authors (searching by the first letter of the last name, using command buttons for selection). In this application, we use the DAO data control, so it can be built using either Visual Basic 5 or Visual Basic 6. If desired, you could also build it using the ADO data control or ADO data environment. There is a lot to learn from in this example. You’ll see how to form a SQL command in code, how get that statement into code, how to set up convenient search mechanisms, and how to build a nice interface, all topics covered in detail in Chapter 6. 1. Start a new project. Add a DAO data control, a DBGrid control and two

command buttons. Position and resize the controls until the form looks something like this:

Page 156: VB6 DB Manual

Visual Basic and Databases

© LAP II

clvi

2. Set properties for the form and controls:

Form1: Name frmBooks BorderStyle 1-Fixed Single Caption Books Database

Data1:

Name datBooks Caption Books DatabaseName BIBLIO.MDB (point to your working copy)

Command1:

Name cmdLetter Caption A Index 0 (we’re building a control array)

Command2:

Name cmdAll Caption Show All Records

DBGrid1:

Name grdBooks DataSource datBooks

As in Example 5-1, you may choose to replace the DAO data control with the ADO data control and the DAO data grid control with the corresponding ADO data grid control (we’ve done this and included it as Example5-2AD in our solutions). If so, use the same properties for the grid control and the data control with one exception. Recall the ADO data control does not have a DatabaseName property. If using the ADO control, set the ConnectionString property such that it points to your working copy of the BIBLIO.MDB database. No code changes are necessary – the code that works for the DAO data control will work for the ADO data control.

Page 157: VB6 DB Manual

Contents

© LAP II

clvii

When you attempt setting the DataSource property for the grid control, you will get this error message:

This error is acceptable since we will be setting the data control’s RecordSource at run-time. You may also get this error when running the application. If so, just click OK. For your reference, we have built an ADO version of the Searching the Books Database program and included it with the example files (look for the example project file with the AD suffix). At this point, the form should appear similar to this:

3. Place these lines in the General Declarations area:

Option Explicit Dim SQLAll As String

SQLAll will be the variable that holds the default SQL statement.

Page 158: VB6 DB Manual

Visual Basic and Databases

© LAP II

clviii

4. Place this code in the Form_Load event procedure:

Private Sub Form_Load() Dim I As Integer 'Size search buttons cmdLetter(0).Width = (frmBooks.ScaleWidth - 2 * cmdLetter(0).Left) / 26 'Create 25 new buttons 'Position new button next to prior button For I = 1 To 25 Load cmdLetter(I) cmdLetter(I).Left = cmdLetter(I - 1).Left + cmdLetter(0).Width cmdLetter(I).Caption = Chr(Asc("A") + I) cmdLetter(I).Visible = True Next I 'Build basic SQL statement SQLAll = "SELECT Authors.Author,Titles.Title,Publishers.[Company Name] " SQLAll = SQLAll + "FROM Authors, Titles, Publishers, [Title Author] " SQLAll = SQLAll + "WHERE Titles.ISBN = [Title Author].ISBN " SQLAll = SQLAll + "AND Authors.Au_ID = [Title Author].Au_ID " SQLAll = SQLAll + "AND Titles.PubID = Publishers.PubID " End Sub

This routine establishes the search buttons A through Z using the cmdLetter control array. It determines button width and places them accordingly. Study the code that does this - it’s very useful. This routine also builds the default SQL statement that gets the Author, Title, and Publisher from the database. Note the statement is built in several stages, each stage appending another clause to the statement. Note, particularly, each subsequent clause has a space at the end to make sure there are no ‘run-ons’ of keywords.

5. Place this code in the Form_Activate event procedure:

Private Sub Form_Activate() 'Show all records initially Call cmdAll_Click End Sub This routine initializes the data grid to the default data view (all records).

Page 159: VB6 DB Manual

Contents

© LAP II

clix

6. Place this code in the cmdAll_Click event procedure:

Private Sub cmdAll_Click() 'Show all records datBooks.RecordSource = SQLAll + "ORDER BY Authors.Author" datBooks.Refresh End Sub This restores the displayed data to all records using the default SQL statement, appended with the ORDER BY clause.

7. Place this code in the cmdLetter_Click event procedure:

Private Sub cmdLetter_Click(Index As Integer) If Index <> 25 Then 'Key other than Z clicked 'Append to SQLAll to limit records to letter clicked datBooks.RecordSource = SQLAll + "AND Authors.Author > '" + cmdLetter(Index).Caption + " ' " datBooks.RecordSource = datBooks.RecordSource + "AND Authors.Author < '" + cmdLetter(Index + 1).Caption + " ' " Else 'Z Clicked 'Append to SQLAll to limit records to Z Authors datBooks.RecordSource = SQLAll + "AND Authors.Author > 'Z' " End If datBooks.RecordSource = datBooks.RecordSource + "ORDER BY Authors.Author" datBooks.Refresh End Sub This routine implements the search on author name. It simply determines what button was clicked by the user and appends an additional test (using AND) to the WHERE clause in the default SQL statement. This test limits the returned records to author’s names between the clicked letter and the next letter in the alphabet. Note that clicking Z is a special case.

Page 160: VB6 DB Manual

Visual Basic and Databases

© LAP II

clx

8. Save the application. Run it. You should see:

Notice how the search buttons are built and nicely displayed. Notice, too, that all records are displayed. Click one of the search buttons. Only records with author names matching the clicked letter will be displayed.

Page 161: VB6 DB Manual

Contents

© LAP II

clxi

Summary • We’re now done with our long journey into the world of SQL. This has been a

relatively complete overview and you will learn more as you become a more proficient database programmer. SQL is at the heart of obtaining a virtual view of desired database information.

• Forming this virtual view using SQL was seen to be a straightforward, and

sometimes complicated, process. Tools such as the Access SQL Builder and the SQL Build function of the ADO data environment can help us build error free SQL queries. Even with such tools, it is important to know SQL so you can understand and modify SQL statements built and implemented by others.

• SQL also has the ability to modify information in a database. You can also use

SQL to add records, delete records, and even create new database tables. But, such capabilities are beyond this course. Besides, the same abilities are available to us using Visual Basic. That is the approach we will use for actual database management tasks. Such tasks using are covered in Chapter 7, following a discussion of building a proper Visual Basic interface in Chapter 6.

Page 162: VB6 DB Manual

Visual Basic and Databases

© LAP II

clxii

Exercise 5

Northwind Traders Database This exercise gives you more practice with SQL by looking at another database - the Northwind Traders database (NWIND.MDB) studied as exercises in other chapters. This is an “open” exercise where you can do what you want until you feel you are more proficient in understanding SQL. First, modify the SQL Tester in Example 5-1 so it uses NWIND.MDB (change the DatabaseName property for the data control). Now, try things. Use SQL to examine each of the eight tables (Categories, Customers, Employees, Order Details, Orders,.Products, Shippers, Suppliers). Examine each field. Try selecting specific fields from tables. Try ordering the results. Try combining tables to show various information. Try the SQL aggregate functions to do some math. Use Access’s ability to generate SQL statements. Cut and paste those statements into SQL Tester to try them. As in Example 5-1, you may choose to replace the DAO data control with the ADO data control and the DAO data grid control with the corresponding ADO data grid control (our examples include such a modified example – Exercise5AD). If so, use the same properties for the grid control and the data control with one exception. Recall the ADO data control does not have a DatabaseName property. If using the ADO control, set the ConnectionString property such that it points to your working copy of the NWIND.MDB database. No code changes are necessary – the code that works for the DAO data control will work for the ADO data control.

Page 163: VB6 DB Manual

Contents

© LAP II

clxiii

When you attempt setting the DataSource property for the grid control, you will get this error message:

This error is acceptable since we will be setting the data control’s RecordSource at run-time. You may also get this error when running the application. If so, just click OK. For your reference, we have built an ADO version of the Northwind Traders Database program and included it with the example files (look for the exercise project file with the AD suffix).

Page 164: VB6 DB Manual

Visual Basic and Databases

© LAP II

clxiv

Visual Basic and Databases

6. Visual Basic Interface Design Review and Preview • At this point in the course, we can use Visual Basic (with either DAO or ADO

technology) to connect to a database and SQL statements allow us to obtain any view of the database information we desire. But, that’s all we can do - view the data. We now want to know how to allow a user to interact with the data - obtain alternate views, modify it, add to it, delete it. To do this, we need a well-designed user interface.

• In this chapter, we look at some design considerations for the Visual Basic

front-end. We examine the toolbox controls and Visual Basic coding techniques needed to build a useful interface and application. Several examples illustrate use of the tools and techniques.

Page 165: VB6 DB Manual

Contents

© LAP II

clxv

Interface Design Philosophy • The design philosophy for a proper application interface is very basic – keep it

as simple as possible and as intuitive as possible. By doing this, you will save yourself (the programmer) and your users a lot of problems. This may be an obvious statement, but you would be surprised at how many programmers do not follow it.

• A first consideration should be to determine what processes and functions

you want your application to perform. What are the inputs and outputs? Develop a framework or flow chart of all your application's processes. Possible functions of a database interface include: data entry, searching, deleting information, adding information, editing information, sorting data, and printing capabilities.

• Decide if multiple forms are required. Decide what controls from the Visual

Basic toolbox you need. Do the built-in Visual Basic tools and functions meet your needs? Do you need to develop some tools or functions of your own? Do you need to acquire some third-party controls?

• Minimize the possibility of user errors. This is a very important step. The fewer

errors your user can make, the less error checking you have to do. If a particular input calls for numeric data, make sure your user can’t type in his name. Choose ‘point and click’ type tools whenever they can be used to replace tools requiring the user to type in something. For example, let the user point at a month of the year, rather than have the user type in the month. If you can avoid letting your user type anything, do it! Every “typed input” requires some kind of validation that means extra work on your part.

• At all steps in the application, make it intuitive to the user what he or she is to

do. Don’t make or let the user guess. You, as the programmer, control the flow of information from the user to the program and vice versa. Maintain that control at all times. Try to anticipate all possible ways a user can mess up in using your application. It's fairly easy to write an application that works properly when the user does everything correctly. It's difficult to write an application that can handle all the possible wrong things a user can do and still not bomb out. And, although it is difficult, it is straightforward and just a matter of following your common sense.

Page 166: VB6 DB Manual

Visual Basic and Databases

© LAP II

clxvi

• Make your interface appealing to the user. Use tolerable colors and don’t get carried away with too many font types. Make sure there are no misspellings (a personal pet peeve). Make the interface consistent with other Windows applications. Familiarity is good in program design. It is quite proper to ‘borrow’ ideas from other applications.

• Although not part of the interface the user sees, you should make your code

readable and traceable - future code modifiers will thank you. Choose meaningful variable and control names. Use comments to explain what you are doing. Consider developing reusable code - modules with utility outside your current development. This will save you time in future developments.

• Debug your application completely before distributing it. There's nothing worse

than having a user call you to point out flaws in your application. A good way to find all the bugs is to let several people try the code - a mini beta-testing program. Let’s illustrate some of these philosophies with an example.

Page 167: VB6 DB Manual

Contents

© LAP II

clxvii

Example 6-1

Mailing List Revisited Open and run the mailing list example built in Chapter 1 (Example 1). It illustrates many of the interface design philosophies just discussed. Notice the program flow - how it directs the user about what to do and minimizes the possibility of errors. In particular, note: ⇒ You cannot type Address Information unless the timer has started

(controlled via the Enabled property of fraMail). ⇒ When the Address Information frame is active, the cursor appears in the

first text box, so the user starts typing the Name field first (controlled with the txtInput text box SetFocus method).

⇒ After the user types information in each text box, hitting <Enter> or <Tab> automatically moves them to the next text box (controlled with the SetFocus method and the TabIndex property).

⇒ After the user types in the last text box (Zip), the focus moves to the Accept command button, so a simple <Enter> accepts the mailing label (using SetFocus on the cmdAccept button).

Notice how the program flow leads the user through the input process. Regarding the timer portion of the application, notice the Pause button is faded (Enabled is False) initially and is only active (Enabled is True) when the timer is running. The other timer control buttons toggle accordingly. There is some validation of inputs in this application also. If there are not five values input, a message box appears informing the user of his error. And, only numbers can be typed when txtInput (Index =4) is active (done in the KeyPress event). This is the box for the Zip that can only be a number. It would probably be more proper to also make sure the entered zip matches either the five or nine digit zip code format. Another validation possible would be to provide a list box control with the 50 states (apologies to our foreign readers for using a provincial example) to choose from instead of asking the user to type in a state name. Regarding the code in the example, notice the use of comments to explain what is happening in each procedure. This helps others read and understand your code. It also helps you know what you were doing when you look back on the code a year later. Also notice that selection of proper variable and control names aids in understanding what is going on in the code portion of the application. Now, let’s look at interface design in more detail.

Page 168: VB6 DB Manual

Visual Basic and Databases

© LAP II

clxviii

Visual Basic Standard Controls • The first step in building a Visual Basic interface is to ‘draw’ the application on

a form. We place the required controls on the form, set properties, and write BASIC code for the needed event and general procedures. As the interface designer, you need to decide which controls best meet your needs regarding efficiency, applicability, and minimization of error possibilities.

• In this section, we briefly look at the standard Visual Basic controls (available

with both DAO and ADO technologies). We examine how they might be used in a database ‘front-end’ and present some of the important properties, events, and methods associated with these controls. This information is provided as a quick review of what is available in the Visual Basic toolbox - a “one-stop” reference to controls and how they are used with databases. A later look at custom controls will complete the reference.

Form Control • The Form is where the user interface is drawn. It is central to the development

of Visual Basic applications, whether for databases or other uses. • Form Properties:

Appearance Selects 3-D or flat appearance. BackColor Sets the form background color. BorderStyle Sets the form border to be fixed or sizeable. Caption Sets the form window title. Enabled If True, allows the form to respond to mouse and keyboard

events; if False, disables form and all controls. Font Sets font type, style, size. ForeColor Sets color of text or graphics. Visible If False, hides the form.

• Form Events:

Activate Form_Activate event is triggered when form becomes the

active window. Click Form_Click event is triggered when user clicks on form. DblClick Form_DblClick event is triggered when user double-clicks

on form. Load Form_Load event occurs when form is loaded. This is a

good place to initialize variables and set any run-time properties.

Page 169: VB6 DB Manual

Contents

© LAP II

clxix

Command Button Control

• The command button is probably the most widely used control. It is used to

begin, interrupt, or end a particular process. With databases, it is used to navigate among records, add records, and delete records.

• Command Button Properties:

Appearance Selects 3-D or flat appearance. BackColor Background color of button (applies only if Style is

Graphical). Cancel Allows selection of button with Esc key (only one button on

a form can have this property True). Caption String to be displayed on button. Default Allows selection of button with Enter key (only one button

on a form can have this property True). Font Sets font type, style, size. Picture Picture appearing on button (applies only if Style is

Graphical). Style Button can be Standard or Graphical.

• Command Button Event:

Click Event triggered when button is selected either by clicking on it or by pressing the access key.

• Command Button Method:

SetFocus Places the focus on the command button.

Page 170: VB6 DB Manual

Visual Basic and Databases

© LAP II

clxx

Label Control

• A label is a control you use to display text. The text in a label can be changed

at run-time in response to events. It is widely used in database applications for information display.

• Label Properties:

Alignment Aligns caption within border. Appearance Selects 3-D or flat appearance. BackColor Background color of label. BorderStyle Determines type of border. Caption String to be displayed in box (property bound to database). DataField Field in database table, specified by DataSource (or

DataMember), bound to label (DAO or ADO). DataMember Specifies the Command object establishing the database

table (ADO data environment only). DataSource Specifies the data control (DAO or ADO) or data

environment (ADO) the label is bound to. Font Sets font type, style, size. ForeColor Color of text in label.

• Label Events:

Click Event triggered when user clicks on a label. DblClick Event triggered when user double-clicks on a label.

Page 171: VB6 DB Manual

Contents

© LAP II

clxxi

Text Box Control

• A text box is used to display information entered at design time, by a user at

run-time, or assigned within code. The displayed text may be edited. This is the tool used in database applications for editing fields.

• Text Box Properties:

Appearance Selects 3-D or flat appearance. BackColor Background color of text box. BorderStyle Determines type of border. DataField Field in database table, specified by DataSource (or

DataMember), bound to text box (DAO or ADO). DataMember Specifies the Command object establishing the database

table (ADO data environment only). DataSource Specifies the data control (DAO or ADO) or data

environment (ADO) the text box is bound to. Font Sets font type, style, size. ForeColor Color of text in text box. Locked When True, the text box contents cannot be edited. MultiLine Specifies whether text box displays single line or multiple

lines. ScrollBars Determines what scroll bars (if any) appear. Text Displayed text (property bound to database).

• Text Box Events:

Change Triggered every time the Text property changes. LostFocus Triggered when the user leaves the text box. This is a

good place to examine the contents of a text box after editing.

KeyPress Triggered whenever a key is pressed. Used for key trapping, as seen in Example 6-1.

• Text Box Methods:

SetFocus Places the cursor in a specified text box.

Page 172: VB6 DB Manual

Visual Basic and Databases

© LAP II

clxxii

Check Box Control

• Check boxes provide a way to make choices from a list of potential

candidates. Some, all, or none of the choices in a group may be selected. With databases, check boxes are used for many kinds of choices.

• Check Box Properties:

Caption Identifying text next to box. DataField Field in database table, specified by DataSource (or

DataMember), bound to check box (DAO or ADO). DataMember Specifies the Command object establishing the database

table (ADO data environment only). DataSource Specifies the data control (DAO or ADO) or data

environment (ADO) the check box is bound to. Font Sets font type, style, size for Caption. Value Indicates if unchecked (0, vbUnchecked), checked (1,

vbChecked), or grayed out (2, vbGrayed) (property bound to database).

• Check Box Event:

Click Triggered when a box is clicked. Value property is automatically changed by Visual Basic.

Page 173: VB6 DB Manual

Contents

© LAP II

clxxiii

Option Button Control

• Option buttons provide the capability to make a mutually exclusive choice

among a group of potential candidate choices. Hence, option buttons work as a group, only one of which can have a True (or selected) value. Option buttons on a form work as an independent group as do groups of options buttons within frames. Option buttons are not data bound controls, yet they can still be used for a variety of options in database interfaces.

• Option Button Properties:

Caption Identifying text next to button. Font Sets font type, style, size. Value Indicates if selected (True) or not (False). Only one option

button in a group can be True. One button in each group of option buttons should always be initialized to True at design time.

• Option Button Event:

Click Triggered when a button is clicked. Value property is automatically changed by Visual Basic.

Frame Control

• Frames provide a way of grouping related controls on a form. Option buttons

within a frame act independently of other option buttons in an application. • Frame Properties:

Caption Title information at top of frame. Font Sets font type, style, size.

Page 174: VB6 DB Manual

Visual Basic and Databases

© LAP II

clxxiv

Picture Box Control

• The picture box allows you to place graphics information on a form. In a

database, picture boxes are used to store graphic data. • Picture Box Properties:

AutoSize If True, box adjusts its size to fit the displayed graphic. DataField Field in database table, specified by DataSource (or

DataMember), bound to picture box (DAO or ADO). DataMember Specifies the Command object establishing the database

table (ADO data environment only). DataSource Specifies the data control (DAO or ADO) or data

environment (ADO) the picture box is bound to. Picture Establishes the graphics file to display in the picture box

(property bound to database). Image Control

• An image control is very similar to a picture box in that it allows you to place

graphics information on a form. The advantage to an image control is its ability to scale displayed graphics.

• Image Box Properties:

DataField Field in database table, specified by DataSource (or DataMember), bound to image control (DAO or ADO).

DataMember Specifies the Command object establishing the database table (ADO data environment only).

DataSource Specifies the data control (DAO or ADO) or data environment (ADO) the image control is bound to.

Picture Establishes the graphics file to display in the image box (property bound to database).

Stretch If False, the image box resizes itself to fit the graphic. If True, the graphic resizes to fit the control area.

Page 175: VB6 DB Manual

Contents

© LAP II

clxxv

Example 6-2

Authors Table Input Form In Chapter 7, we will build a complete database management system for the books database. Each table in the database will require some kind of input form. In this chapter, we build such a form for the Authors table. Even though it is a very simple table (only three fields: Au_ID, Author, Year Born), it provides an excellent basis to illustrate many of the steps of proper interface design. We need an input form that allows a user to edit an existing record, delete an existing record or add a new record. The form should also allow navigation from one record to another. The books database management example (including the Authors input form) will be built using the DAO data control. If you prefer to use either the ADO data control or ADO data environment, we provide needed modification steps. These steps will be in shaded boxes. In the code accompanying this course, we use a special naming convention for all files (projects, forms) to distinguish among examples built using each technology. The convention is: FileName (no suffix, DAO data control) FileNameAD (AD suffix, ADO data control) FileNameDE (DE suffix, ADO data environment) For this particular example, the three project file and form names are: Example6-2 (DAO), Example6-2AD (ADO data control) and Example6-2DE (ADO data environment). This is the same convention used in Chapter 5 for the SQL tester. We suggest you adopt a similar naming convention if building multiple versions of the examples.

Page 176: VB6 DB Manual

Visual Basic and Databases

© LAP II

clxxvi

The steps to follow: 1. Start a new application. We need three label controls and three text boxes to

display the fields. We need two command buttons to move from one record to the next. We need five command buttons to control editing features and one command button to allow us to stop editing. Lastly, a DAO data control is needed. Place these controls on a form. The layout should resemble:

ADO Data Control Modification Use an ADO data control instead of the DAO data control.

ADO Data Environment Modification Add an ADO data environment to the project instead of the DAO data control.

Page 177: VB6 DB Manual

Contents

© LAP II

clxxvii

2. Set these properties for the form and controls:

Form1: Name frmAuthors BorderStyle 1-Fixed Single Caption Authors

Data1:

Name datAuthors DatabaseName BIBLIO.MDB (point to your copy) RecordSource SELECT * FROM Authors ORDER BY Author Visible False

ADO Data Control Modifications Adodc1: Name datAuthors CommandType 1-adCmdText ConnectionString Use the Build option to point to the

BIBLIO.MDB database RecordSource SELECT * FROM Authors ORDER BY

Author Visible False

ADO Data Environment Modifications 1. Name the data environment denBooks. Name the connection

object conBooks. Right-click conBooks and set Properties so it points to your working copy of BIBLIO.MDB.

2. Add a command object. Assign these properties: Command1: Name comAuthors ConnectionName conBooks CommandType 1-adCmdText CommandText SELECT * FROM Authors ORDER BY

Author

Page 178: VB6 DB Manual

Visual Basic and Databases

© LAP II

clxxviii

Label1: Caption Author ID

Text1:

Name txtAuthorID DataSource datAuthors DataField Au_ID Locked True

ADO Data Environment Modifications Text1: Name txtAuthorID DataSource denBooks DataMember comAuthors DataField Au_ID Locked True

Label2:

Caption Author Name Text2:

Name txtAuthor DataSource datAuthors DataField Author Locked True

ADO Data Environment Modifications Text2: Name txtAuthor DataSource denBooks DataMember comAuthors DataField Author Locked True

Page 179: VB6 DB Manual

Contents

© LAP II

clxxix

Label3: Caption Year Born

Text3:

Name txtYearBorn DataSource datAuthors DataField Year Born Locked True

ADO Data Environment Modifications Text3: Name txtYearBorn DataSource denBooks DataMember comAuthors DataField Year Born Locked True

Command1:

Name cmdPrevious Caption <= Previous

Command2:

Name cmdNext Caption Next =>

Command3:

Name cmdEdit Caption &Edit

Command4:

Name cmdSave Caption &Save

Page 180: VB6 DB Manual

Visual Basic and Databases

© LAP II

clxxx

Command5: Name cmdCancel Caption &Cancel

Command6:

Name cmdAddNew Caption &Add New

Command7:

Name cmdDelete Caption &Delete

Command8:

Name cmdDone Caption Do&ne

Note, we lock (Locked = True) all the text boxes. We will unlock them when we (as the programmer) decide the user can change a value (remember, we are in control). At this point, the form should appear as:

Page 181: VB6 DB Manual

Contents

© LAP II

clxxxi

3. We will add features to this input application as we progress through the chapter. At this point, we add code to allow us to navigate through the Authors table records. There are two event procedures to code. First, the cmdPrevious_Click event:

Private Sub cmdPrevious_Click() datAuthors.Recordset.MovePrevious If datAuthors.Recordset.BOF Then datAuthors.Recordset.MoveFirst End If End Sub

And, the cmdNext_Click event:

Private Sub cmdNext_Click() datAuthors.Recordset.MoveNext If datAuthors.Recordset.EOF Then datAuthors.Recordset.MoveLast End If End Sub

ADO Data Environment Modification In above code, replace all occurrences of datAuthors.Recordset with denBooks.rscomAuthors. This incorporates the data environment’s convention for naming the recordset.

4. Save the application. Run it. Navigate among the records. Note you cannot

edit anything. The text boxes are locked. As we progress through this chapter (and the next), we will continue to add features to this example until it is complete.

Page 182: VB6 DB Manual

Visual Basic and Databases

© LAP II

clxxxiiMessage Box • Many times, in a database application, you will want to impart some information

to your user. That information may be a courtesy message (“New record written”) or a question requiring feedback (“Do you really want to delete this record?”). Visual Basic (and Windows) provides an excellent medium for providing such information – the message box.

• A message box displays a message, an optional icon, and a selected set of

command buttons. The user responds to the message box by clicking one of the button(s). If you’ve done any work in the Windows environment, you have seen message boxes. For example, here’s one that appears in Visual Basic when the floppy disk drive is not ready:

The user responds by fixing the problem and clicking Retry (the default response) or by clicking Cancel. Visual Basic then takes the necessary actions depending on user response. We can add this same capability to our Visual Basic database applications. The great thing about the message box is that it is familiar to the user (familiarity is good) and it is easy to use.

• To use a message box in BASIC code requires just one line of code. There

are two forms for the message box. The statement form returns no value (it simply displays the box). The code syntax is:

MsgBox Message, Type, Title where Message Text of message to be displayed (string) Type Type of message box (integer, discussed in a bit) Title Text in title bar of message box (string) You have no control over where the message box appears on the screen (it is usually centered).

Page 183: VB6 DB Manual

Contents

© LAP II

clxxxiii

• The function form of the message box returns an integer value (corresponding to the button clicked by the user). Example of use (Response is returned value):

Dim Response as Integer Response = MsgBox(Message, Type, Title)

• The Type argument is formed by summing four values corresponding to the

button(s) to display, any icon to show, which button is the default response, and the modality of the message box.

• The first component of the Type value specifies the buttons to display:

Value Meaning Symbolic Constant 0 OK button only vbOKOnly 1 OK/Cancel buttons vbOKCancel 2 Abort/Retry/Ignore buttons vbAbortRetryIgnore 3 Yes/No/Cancel buttons vbYesNoCancel 4 Yes/No buttons vbYesNo 5 Retry/Cancel buttons vbRetryCancel

Pick the set of buttons that meets your need.

• The second component of Type specifies the icon to display in the message box:

Value Meaning Symbolic Constant

0 No icon (None) 16 Critical icon vbCritical 32 Question mark vbQuestion 48 Exclamation point vbExclamation 64 Information icon vbInformation

Pick an icon that corresponds to the displayed message.

• The third component of Type specifies which button is default (i.e. pressing

Enter is the same as clicking the default button):

Value Meaning Symbolic Constant 0 First button default vbDefaultButton1 256 Second button default vbDefaultButton2 512 Third button default vbDefaultButton3

Always try to make the default response the “least damaging,” if the user just blindly accepts it.

Page 184: VB6 DB Manual

Visual Basic and Databases

© LAP II

clxxxiv• The fourth and final component of Type specifies the modality:

Value Meaning Symbolic Constant 0 Application modal vbApplicationModal 4096 System modal vbSystemModal

If the box is Application Modal, the user must respond to the box before continuing work in the current application. If the box is System Modal, all applications are suspended until the user responds to the message box.

• Note for each option in Type, there are numeric values listed and symbolic

constants. It is strongly suggested that the symbolic constants be used instead of the numeric values. You should agree that vbOKOnly means more than the number 0 when selecting the button type.

• The value returned by the function form of the message box is related to the

button clicked:

Value Meaning Symbolic Constant 1 OK button selected vbOK 2 Cancel button selected vbCancel 3 Abort button selected vbAbort 4 Retry button selected vbRetry 5 Ignore button selected vbIgnore 6 Yes button selected vbYes 7 No button selected vbNo

• Message boxes should be used whenever your application needs to inform the

user of action or requires user feedback to continue. It is probably better to have too many message boxes, than too few. You always want to make sure your application is performing as it should and the more information you have, the better.

Page 185: VB6 DB Manual

Contents

© LAP II

clxxxv

Example 6-3

Authors Table Input Form (Message Box) There are two places where we could use message boxes in the Authors Table example. A statement form after saving an update to let the user know the save occurred and a function form related to deleting records. 1. Load Example 6-2 completed earlier. We will modify this example to include

message boxes.

ADO Data Control Modification Load Example6-2AD (the ADO data control version).

ADO Data Environment Modification Load Example6-2DE (the ADO data environment version).

2. Attach this code to the cmdSave_Click event:

Private Sub cmdSave_Click() MsgBox "Record saved.", vbOKOnly + vbInformation, "Save" End Sub

Obviously, there will be more code in this event as we continue with this example. This code just implements the message box.

3. Attach this code to the cmdDelete_Click event:

Private Sub cmdDelete_Click() Dim Response As Integer Response = MsgBox("Are you sure you want to delete this record?", vbYesNo + vbQuestion + vbDefaultButton2, "Delete") If Response = vbNo Then Exit Sub End If End Sub

Page 186: VB6 DB Manual

Visual Basic and Databases

© LAP II

clxxxvi

Note we exit the procedure if the user selects No. And, notice the No button is default – this makes the user think a bit before hitting Enter. Like above, there will be more code in this procedure as we proceed.

4. Save the application and run it. Click the Save and Delete buttons to see how

the message boxes appear.

Page 187: VB6 DB Manual

Contents

© LAP II

clxxxvii

Application State • When presenting a Visual Basic database interface to a user, it should be

obvious, to the user, what needs to be done. Options should be intuitive and the possibility of mistakes minimized, if not completely eliminated. To maintain this obvious quality, you should always be aware of what state your application is in.

• Application state implies knowing just what is currently being done within the

interface. Are you adding a record, editing a record, deleting a record, or perhaps leaving the application? Once you know the state the application is in, you adjust the interface so that options needed for that particular state are available to the user. You also need to know when and how to transition from one state to another.

• What options are adjusted to reflect application state? A primary option is a

control’s Enabled property. By setting Enabled to False, you disable a control, making it unavailable to the user. So, if the user is not able to save a current record, the command button that does the save should have an Enabled property of False. A more drastic disabling of a control is setting its Visible property to False. In this case, there is no misunderstanding about application state. As the application moves from one state to another, you need to determine which controls should be enabled and which should be disabled.

• For text box controls, a property of importance is the Locked property. If a

value in a text box is not to be edited, set Locked to True. When editing is allowed (the state changes), toggle the Locked property to False. For text boxes that are always locked (used for display, not editing purposes), use color (red is good) to indicate they are not accessible. When editing in a text box, use the SetFocus method to place the cursor in the box, making it the active control (giving it focus) and saving the user a mouse click. The SetFocus method can also be used to programmatically move the user from one text box to the next in a desired order.

Page 188: VB6 DB Manual

Visual Basic and Databases

© LAP II

clxxxviii• Another mechanism for moving from one control to another in a prescribed

order is the TabIndex property, in conjunction with TabStop. If TabStop is True, TabIndex defines the order controls become active (only one control can be active at a time) as the <Tab> key is pressed (the order is reversed when <Shift>-<Tab> is pressed). When controls are placed on a form at design time, they are assigned a TabIndex value with TabStop = True. If you don’t want a control to be made active with <Tab>, you need to reset its TabStop property to False. If the assigned order is not acceptable, reset the TabIndex properties for the desired controls, starting with a low number and increasing that value with each control added to the <Tab> sequence. A primary application for <Tab> sequencing is moving from one text box to the next in a detailed input form.

• If the concepts of control focus and tab movements are new or unfamiliar, try

this. Start a new application in Visual Basic. Add three command buttons (Command1, Command2, Command3), then three text boxes (Text1, Text2, Text3). Run the application. The first command button (Command1) should have focus (a little outline box is around the caption). If you press <Enter> at this point, this button is ‘clicked.’ Press the <Tab> key and the focus moves to the second command button. Press <Tab> twice. The focus should now be in the first text box (the cursor is in the box). Keep pressing <Tab> and watch the focus move from one control to the other, always in the same order. Pressing <Shift>-<Tab> reverses the order. Now, for each command button, set the TabStop property to False (removing them from the tab sequence). Re-run the application and you should note the focus only shifts among the text boxes. Try resetting the TabIndex properties of the text boxes to change the shift direction. Always use the idea of focus in your applications to indicate to the user what control is active.

• All of this application state talk may sound complicated, but it really isn’t.

Again, it’s all just a matter of common sense. After you design your interface, sit back and step through your application in the Visual Basic environment, exercising every option available. With each option, ask yourself what the user needs to see. Implement the necessary logic to make sure this is all the user sees. Make sure moves from one state to another are apparent and correct. Try lots of things until you are comfortable with the finished product. The Visual Basic environment makes performing such tasks quite easy.

Page 189: VB6 DB Manual

Contents

© LAP II

clxxxix

Example 6-4

Authors Table Input Form (Application State) The Authors Table Input Form can operate in one of three states: View state, Add state or Edit state. In View state, the user can navigate from record to record, access adding and/or editing records, delete a record, or exit the application. In View state, data cannot be changed. In both Add and Edit states, no navigation should be possible, data can be changed, and the user should have access to the Save and Cancel functions. Each of these states can be implemented using command button Enabled properties and text box Locked properties. We use TabIndex (and TabOrder) to control shift of focus in the text box controls. We will use a general procedure to allow switching from one state to another. 1. Open Example 6-3 in the Visual Basic environment. We will modify this

example to include state considerations.

ADO Data Control Modification Load Example6-3AD (the ADO data control version).

ADO Data Environment Modification Load Example6-3DE (the ADO data environment version).

2. Remove the command buttons from tab sequencing by setting all (eight

buttons) of their TabStop properties to False. Also set TabStop to False for the txtAuthorID text box (we will not edit this value - we’ll explain why later). Set TabIndex for txtAuthor to 1 and TabIndex for txtYearBorn to 2.

3. Add a general Sub procedure named SetState with string argument AppState.

To add this procedure, with the code window active, select Tools and Add Procedure. Fill in the blanks appropriately and a framework appears in the code window.

Page 190: VB6 DB Manual

Visual Basic and Databases

© LAP II

cxc

4. Add this code to the SetState procedure (note, the added AppState argument):

Private Sub SetState(AppState As String) Select Case AppState Case "View" txtAuthorID.BackColor=vbWhite txtAuthor.Locked = True txtYearBorn.Locked = True cmdPrevious.Enabled = True cmdNext.Enabled = True cmdAddNew.Enabled = True cmdSave.Enabled = False cmdCancel.Enabled = False cmdEdit.Enabled = True cmdDelete.Enabled = True cmdDone.Enabled = True txtAuthor.SetFocus Case "Add", "Edit" txtAuthorID.BackColor=vbRed txtAuthor.Locked = False txtYearBorn.Locked = False cmdPrevious.Enabled = False cmdNext.Enabled = False cmdAddNew.Enabled = False cmdSave.Enabled = True cmdCancel.Enabled = True cmdEdit.Enabled = False cmdDelete.Enabled = False cmdDone.Enabled = False txtAuthor.SetFocus End Select End Sub

This code sets the application in View, Add or Edit state. Note which buttons are available and which are not. Notice the Author ID box is red in Add and Edit state to indicate it cannot be changed. Notice that the Add and Edit states are the same (for now) and are just a ‘toggling’ of the View state – this will occur quite often – a great place for ‘cut and paste’ coding. We now need to modify the application code to use this procedure to move from state to state.

Page 191: VB6 DB Manual

Contents

© LAP II

cxci

4. We want to be in the View state when the application is initialized. Attach this code to the Form_Activate event:

Private Sub Form_Activate() Call SetState("View") End Sub

5. When the Add New button is clicked, we want to switch to Add state. Add this

line of code at the top of the cmdAddNew_Click event procedure:

Call SetState("Add") 6. When the Edit button is clicked, we switch to Edit state. Add this line of code

at the top of the cmdEdit_Click event procedure:

Call SetState("Edit") 7. Following a Cancel or Save operation (in Add or Edit state), we want to return

to View state. Place this line at the end of the cmdCancel_Click and cmdSave_Click event procedures:

Call SetState("View")

The Delete button does not need any change of state code – it only works in View state and stays in that state following a delete.

8. We’re almost done. This is a small change, but an important one that gives

your application a professional touch. Notice that if you click the Previous button and the recordset pointer is at the first record, nothing changes. Similarly, at the end of the recordset, if you click Next, nothing changes. This lack of change might confuse the user. To give the user some feedback that they’ve reached a limit, I like to provide some audible feedback. In both the cmdPrevious_Click and cmdNext_Click procedures, add the Visual Basic Beep statement within the If/End If structure. Then, when the user bumps a limit, a little beep is heard.

9. Save and run the application. Notice how the various buttons change state as

different functions are accessed on the interface form. In Add and Edit state (the ID box is red), check the tab order of the two text boxes (a very short tab order!). A warning – if you change any value in Add or Edit mode, it will be saved in the database (a feature of the Jet engine). In each state, it is obvious to the user what functions are available and when they are available. Do you hear the beep when you try to move past a limit at the end or beginning of the recordset?

Page 192: VB6 DB Manual

Visual Basic and Databases

© LAP II

cxcii

Entry Validation • Throughout your work with databases, you will find that viewing database

information is an easy task with Visual Basic. Things quickly become difficult, though, when you want to modify information in a database. And, things become very difficult when you allow your user to type information. That’s why, if at all possible, don’t allow your user to type things. Use point and click type controls whenever possible.

• Checking input information from a user requires programming on your part.

You must insure information being put in a database is correct. There are two steps to checking information from a user: entry validation and input validation. Entry validation is associated with text box controls and checks for proper keystrokes. Input validation is associated with several control types and checks to make sure entries and choices meet certain requirements. In this section, we address entry validation. Input validation is addressed in the next section of this chapter.

• As mentioned, entry validation checks for proper keystrokes. For example, if a

numerical entry is needed, only allow the pressing of number keys. If spaces are not allowed, don’t allow them. If an input must be in upper case letters, don’t allow lower case letters to be typed. Restricting keystrokes is referred to as key trapping.

• Key trapping is done in the KeyPress event procedure of a text box. Such a

procedure has the form (for a text box named txtText):

Sub txtText_KeyPress (KeyAscii as Integer) . . . End Sub

In this procedure, every time a key is pressed in the corresponding text box, the ASCII code for the pressed key is passed to the procedure as the argument KeyAscii. With key trapping, if KeyAscii is an acceptable value, we do nothing. If KeyAscii is not acceptable, we set KeyAscii equal to zero and exit the procedure. Doing this has the same result of not pressing a key at all. ASCII values for all keys are available via the on-line help in Visual Basic. The BASIC function Asc can also be used to determine a key’s ASCII code. And some keys are also defined by symbolic constants. Where possible, we will use symbolic constants; else, we will use the ASCII values.

Page 193: VB6 DB Manual

Contents

© LAP II

cxciii

• As an example, say we have a text box (named txtExample) and we only want to be able to enter upper case letters (ASCII codes 65 through 90, or, correspondingly, symbolic constants vbKeyA through vbKeyZ). The KeyPress procedure would look like (the Beep causes an audible tone if an incorrect key is pressed):

Sub txtExample_KeyPress(KeyAscii as Integer) If KeyAscii >= vbKeyA And KeyAscii <= vbKeyZ Then Exit Sub Else KeyAscii = 0 Beep End If End Sub

• In key trapping, it's advisable to always allow the backspace key (ASCII code

8; symbolic constant vbKeyBack) to pass through the KeyPress event. Else, you will not be able to edit the text box properly. Modifying the above example, this code would be:

Sub txtExample_KeyPress(KeyAscii as Integer) If (KeyAscii >= vbKeyA And KeyAscii <= vbKeyZ) Or KeyAscii = vbKeyBack Then Exit Sub Else KeyAscii = 0 Beep End If End Sub

• Rather than just beep when an unacceptable keystroke is encountered, you

can also use key trapping to automatically correct invalid inputs. For example, if the input requires all upper case letters, you can use the BASIC UCase function to convert any lower case letters to upper case letters.

Page 194: VB6 DB Manual

Visual Basic and Databases

© LAP II

cxciv

Example 6-5

Authors Table Input Form (Entry Validation) In the Authors Table Input Form, the Year Born field can only be numeric data. 1. Load Example 6-4 completed earlier. We will modify this example to include

entry validation.

ADO Data Control Modification Load Example6-4AD (the ADO data control version).

ADO Data Environment Modification Load Example6-4DE (the ADO data environment version).

2. Attach this code to the txtYearBorn_KeyPress event (make sure you select

the proper event in the code window – don’t use the Change event!):

Private Sub txtYearBorn_KeyPress(KeyAscii As Integer) If (KeyAscii >= Asc("0") And KeyAscii <= Asc("9")) Or KeyAscii = vbKeyBack Then Exit Sub Else Beep KeyAscii = 0 End If End Sub

3. Save and run the application. Click Edit to switch to Edit state.. Click the Year

Born text box. Try some typing. You should only be able to type numbers (or use the backspace key) in the Year Born entry box.

Page 195: VB6 DB Manual

Contents

© LAP II

cxcv

Input Validation • In the example just studied, although the user can only input numeric data for

the Year Born field, there is no guarantee the final input would be acceptable. What if the input year is past the current year? What if the year is 1492? A second step in validation is to check values in context. Do the input values make sense? Do the values meet established rules? This step is input validation.

• Some common validation rules are:

⇒ Is this field required? If a field is required and no input is provided, this could cause problems.

⇒ Is the input within an established range? For example, if entering a day number for the month of April, is the value between 1 and 30?

⇒ Is the input the proper length? Social security numbers (including hyphens) require 11 characters. If 11 characters are not detected, the input is not a valid social security number. The BASIC Len function can be used here, as can a text box MaxLength property (to limit the length).

⇒ Is the input conditional? Some fields only need to filled in if other fields are filled in. For example, if a user clicks to ship to another address, you need to make sure that address exists.

⇒ Is the input a primary key? If so, and the user has the capability of entering a value, we must insure it is a unique value. Each primary key value in a table must be different.

• The amount of input validation required is dependent on the particular field.

Many times, there is none needed. You, as the programmer, need to examine each input field and answer the questions posed above: is the field required, must it be within a range, is it length restricted, is it conditional? Any Yes answers require BASIC code to do the validation. You will probably find additional questions as you develop your database skills.

• Where does the validation code go? It really depends on what database

technology (DAO or ADO) you are using and how you implement database editing. We will discuss this topic in detail in Chapter 7. For our example we have been creating, we will write a general procedure named ValidateData that is called in the Click event of the Save button. The user clicks this button when done editing, making it a great place to check validity. If any validation rules are violated, we don’t allow the requested change(s).

Page 196: VB6 DB Manual

Visual Basic and Databases

© LAP II

cxcvi

• We see entry and input validation require a bit of programming on our part. But, it is worth it. Field validation insures the integrity of the information we are putting in a database. We always need to maintain that integrity. And, one last time for emphasis (are you getting the idea this is important) – if you can eliminate user typing – do it!

Page 197: VB6 DB Manual

Contents

© LAP II

cxcvii

Example 6-6

Authors Table Input Form (Input Validation) As mentioned, the Year Born must be validated. We will make sure that, if an input is attempted (we won’t require a year be input), the year has no more than four characters, is not greater than the current year and is greater than 150 years prior to the current year (by not hard coding a minimum year, the code automatically upgrades itself). We will also make sure the user enters an Author Name. 1. Load Example 6-5 completed earlier. We will modify this example to include

input validation.

ADO Data Control Modification Load Example6-5AD (the ADO data control version).

ADO Data Environment Modification Load Example6-5DE (the ADO data environment version).

2. Add a procedure named ValidateData with a Boolean argument AllOK (if

True, all validation rules were met). Add this code:

Private Sub ValidateData(AllOK As Boolean) Dim Message As String Dim InputYear As Integer, CurrentYear As Integer AllOK = True Message = "" 'Check for name If Len(txtAuthor.Text) = 0 Then Message = "You must enter an Author Name." + vbCrLf txtAuthor.SetFocus AllOK = False End If 'Check length and range on Year Born InputYear = Val(txtYearBorn.Text) CurrentYear = Val(Format(Now, "yyyy")) If Len(txtYearBorn.Text) <> 0 Then If InputYear > CurrentYear Or InputYear < CurrentYear - 150 Then

Page 198: VB6 DB Manual

Visual Basic and Databases

© LAP II

cxcviii

Message = Message + "Year Born must be between" & Str(CurrentYear - 150) & " and" & Str(CurrentYear) txtYearBorn.SetFocus AllOK = False End If End If If Not (AllOK) Then MsgBox Message, vbOKOnly + vbInformation, "Validation Error" End If End Sub In this code, we first check to see if an Author Name is entered and then validate the Year Born field. If either validation rule is violated, the variable AllOK is set to False and a message box displayed. If any of this code is unfamiliar, try Visual Basic on-line help for assistance.

3. Set MaxLength property for txtYearBorn text box to 4.

4. Modify the cmdSave_Click event to read (new lines are italicized)::

Private Sub cmdSave_Click() Dim Valid As Boolean Call ValidateData(Valid) If Not (Valid) Then Exit Sub MsgBox "Record saved.", vbOKOnly + vbInformation, "Save" Call SetState("View") End Sub This calls the validation routine. If the Valid variable is False upon return from the routine, the data is not valid and we exit the procedure.

4. Save and run the application. Click Edit. Click Edit and blank out the Author

Name. Click Save. A message box should appear. Type an invalid numeric value in the Year Born box. Click Save. A new message should be displayed. Click OK and the focus is reset on the Author Name text box, helping the user. Try a valid year and valid name – make sure they are accepted.

Page 199: VB6 DB Manual

Contents

© LAP II

cxcix

5. After typing a new Author name, to type a Year Born, you need to click in that text box. This clicking (especially when working with lots of text boxes) is cumbersome. A preferred method would be a programmatic shift of focus. Add this code at the top of the txtYearBorn_KeyPress event:

If KeyAscii = vbKeyReturn Then txtAuthor.SetFocus Exit Sub End If

In this code, if the <Enter> key is pressed, the focus is shifted from the Year Born text box to the Author text box (if a valid year is input). This programmatic change of focus is used all the time in database interfaces. Users like to see the focus move when they press <Enter>. It is an additional step in maintaining proper application state. To shift from the Author box to the Year Born box, add this code to the Author_KeyPress event:

Private Sub txtAuthor_KeyPress(KeyAscii As Integer) If KeyAscii = vbKeyReturn Then txtYearBorn.SetFocus Exit Sub End If End Sub

6. Save and run the example again. Click Edit. Notice how the focus shifts

between the two text boxes as you change the values and press <Enter>. Pressing <Tab> should also change the focus appropriately.

Page 200: VB6 DB Manual

Visual Basic and Databases

© LAP II

cc

Error Trapping and Handling • Even with a well-designed, ‘user-proof’ interface, errors can still occur. This is

especially true when working with databases. Occasionally, data cannot be written to, or deleted from, the database or invalid fields are encountered. Without any action on our part, these run-time errors might bring our application to an unceremonious end. If, however, we recognize an error has occurred and inform the user of the problem, we might be able to recover.

• The process of detecting errors before they cause big problems is error

trapping and handling. This process differs from entry and input validation. Entry and input validation are used to prevent errors from occurring. Error trapping and handling is what is needed if an error still occurs.

• There are two steps: error trapping (detecting an error has occurred) and

error handling (deciding what to do about the detected error). Error trapping and handling must be implemented in every procedure in your application where you think it might be needed. Visual Basic does not allow global error trapping. At a minimum, you should implement error trapping and handling in every procedure that writes to or reads from the database.

• Error trapping is enabled with the BASIC On Error statement:

On Error GoTo errlabel

Yes, this uses the dreaded GoTo statement! Any time a run-time error occurs following this line, program control is transferred to the line labeled errlabel. Recall a labeled line is simply a line with the label followed by a colon (:).

• The best way to explain how to use error trapping is to look at an outline of an

example procedure with error trapping.

Sub SubExample() [Declare variables, ...] On Error GoTo HandleErrors [Procedure code] Exit Sub HandleErrors: [Error handling code] End Sub

Page 201: VB6 DB Manual

Contents

© LAP II

cci

Once you have set up the variable declarations, constant definitions, and any other procedure preliminaries, the On Error statement is executed to enable error trapping. Your normal procedure code follows this statement. The error handling code goes at the end of the procedure, following the HandleErrors statement label. This is the code that is executed if an error is encountered anywhere in the Sub procedure. Note you must exit (with Exit Sub) from the code before reaching the HandleErrors line to avoid inadvertent execution of the error handling code.

• Since the error handling code is in the same procedure where an error occurs,

all variables in that procedure are available for possible corrective action. If at some time in your procedure, you want to turn off error trapping, that is done with the following statement:

On Error GoTo 0

You don’t need a line labeled ‘0’ for this to work.

• Once a run-time error occurs, we would like to know what the error is and

attempt to fix it. This is done in the error handling code. Visual Basic offers, through the Err object, help in identifying run-time errors. Three Err object properties of particular interest are:

Number Visual Basic error number Source Name of Visual Basic file in which error has occurred Description A textual description of the error

Consult on-line help for more details Visual Basic run-time error numbers and their descriptions.

Page 202: VB6 DB Manual

Visual Basic and Databases

© LAP II

ccii

• Once an error has been trapped and some action taken, control must be returned to your application. That control is returned via the Resume statement. There are three options:

Resume Lets you retry the operation that caused the error.

That is, control is returned to the line where the error occurred. This could be dangerous in that, if the error has not been corrected (via code or by the user), an infinite loop between the error handler and the procedure code may result.

Resume Next Program control is returned to the line immediately following the line where the error occurred.

Resume label Program control is returned to the line labeled label.

You can also use Exit Sub as an error handling statement. With this, you immediately exit the routine in which the error occurred.

• Development of an adequate error handling procedure is application

dependent. You need to know what type of errors you are looking for and what corrective actions must be taken if these errors are encountered. For example, if a 'divide by zero' is found, you need to decide whether to skip the operation or do something to reset the offending denominator. What we develop here is a generic framework for an error handling procedure. It simply informs the user that an error has occurred, provides a description of the error, and allows the user to Abort, Retry, or Ignore. This framework is a good starting point for designing custom error handling for your database applications.

• The generic code (begins with label HandleErrors) is:

HandleErrors: Select Case MsgBox(Err.Description, vbCritical + vbAbortRetryIgnore, "Error Number" + Str(Err.Number) + " in " + Err.Source) Case vbAbort Exit Sub Case vbRetry Resume Case vbIgnore Resume Next End Select

Page 203: VB6 DB Manual

Contents

© LAP II

cciii

Let’s look at what goes on here. First, this routine is only executed when an error occurs. A message box is displayed, using the Visual Basic provided error description (Err.Description) as the message, uses a critical icon along with the Abort, Retry, and Ignore buttons, and uses the error number Err.Number and Err.Source in the title. This message box returns a response indicating which button the user selected. If Abort is selected, we simply exit the procedure. If Retry is selected, the offending program line is retried (in a real application, you or the user would have to change something here to correct the condition causing the error). If Ignore is selected, program operation continues with the line following the error causing line.

• To use this generic code in an existing procedure, you need to do three things:

1. Copy and paste the error handling code into the end of your procedure. 2. Place an Exit Sub line immediately preceding the HandleErrors labeled

line. 3. Place the line, On Error GoTo HandleErrors, at the beginning of your

procedure. For example, if your procedure is the SubExample seen earlier, the modified code will look like this:

Sub SubExample() [Declare variables, ...] On Error GoTo HandleErrors [Procedure code] Exit Sub HandleErrors: Select Case MsgBox(Err.Description, vbCritical + vbAbortRetryIgnore, "Error Number" + Str(Err.Number) + " in " + Err.Source) Case vbAbort Exit Sub Case vbRetry Resume Case vbIgnore Resume Next End Select End Sub

Again, this is a very basic error-handling routine. You must determine its utility in your applications and make any modifications necessary. Specifically, you need code to clear error conditions before using the Retry option.

Page 204: VB6 DB Manual

Visual Basic and Databases

© LAP II

cciv

• One last thing. Once you've written an error handling routine, you need to test it to make sure it works properly. But, creating run-time errors is sometimes difficult and perhaps dangerous. Visual Basic comes to the rescue! The Visual Basic Err object has a method (Raise) associated with it that simulates the occurrence of a run-time error. To cause an error with value Number, use:

Err.Raise Number

We can use this function to completely test the operation of any error handler we write. Don’t forget to remove the Raise statement once testing is completed, though!

Page 205: VB6 DB Manual

Contents

© LAP II

ccv

Example 6-7

Authors Table Input Form (Error Trapping and Handling) As mentioned, error trapping and handling should be included within every procedure where database information is read or written. It should also be included in procedures where database files are being opened or saved (covered in later chapters). 1. Load Example 6-6 completed earlier. We will modify this example to include

error trapping handling

ADO Data Control Modification Load Example6-6AD (the ADO data control version).

ADO Data Environment Modification Load Example6-6DE (the ADO data environment version).

2. Modify the cmdAddNew_Click, cmdSave_Click, and cmdDelete_Click event

procedures to allow error trapping and handling. Use the generic code developed in this section, taking advantage of ‘cut and paste’ editing.

3. Save the application. After the ‘On Error’ line in the cmdAddNew_Click

procedure, add this line:

Err.Raise 11

Run the application. Click Add New. You should see a message box reporting a ‘divide by zero’ error. Check how the application responds when you click Abort (stays in View state), Retry (keeps displaying an error), or Ignore (goes to Add state). Play around with different error numbers, if you like. Before leaving this example, remove this line of code that generates an error.

Page 206: VB6 DB Manual

Visual Basic and Databases

© LAP II

ccvi

On-Line Help Systems • So, at this point, we know how to build a powerful, intuitive interface, insure

valid inputs, and handle any run-time errors that might occur. Even with all this work, there still may be times when the user is stumped as to what to do next. Instinct tells the user to press the <F1> function key. Long ago, someone in the old DOS world decided this would be the magic “Help Me!” key. Users expect help when pressing <F1> (I’m sure you rely on it a lot when using Visual Basic). If nothing appears after pressing <F1>, user frustration sets in – not a good thing.

• All applications written for other than your personal use should include some

form of an on-line help system. It doesn’t have to be elegant, but it should be there. Adding a help file to your Visual Basic application will give it real polish, as well as making it easier to use. In this section, we will show you how to build a very basic on-line help system for your database applications. This system will simply have a list of help topics the user can choose from.

• The on-line help system will be built using the Microsoft Help Compiler

Workshop which ships with Visual Basic. It is located in the \Tools\HCW folder of the Visual Basic installation CD and must be installed separately (see the CD for instructions). Your help file can contain text and graphics information needed to be able to run your application. The help file will be displayed by the built-in Windows help utility that you (and your users – again, familiarity is good) use with every Windows application, hence all functions available with that utility are available with your help system. For example, each file can contain one or more topics that your user can select by clicking a hot spot, using a keyword search, or browsing through text. And, it’s easy for your user to print any or all help topics.

Page 207: VB6 DB Manual

Contents

© LAP II

ccvii

• Creating a complete help file is a major task and sometimes takes as much time as creating the application itself! Because of this, we will only skim over the steps involved, generate a simple example, and provide guidance for further reference. There are six major steps involved in building your own help file:

1. Create your application and develop an outline of help system topics. 2. Create the Help Text File (or Topic File) in RTF format (RTF

extension). 3. Create a Help Contents File (CNT extension). 4. Create the Help Project File (HPJ extension). 5. Compile the Help File using the Help Compiler and Project File. 6. Attach the Help File to your Visual Basic application.

Step 1 is application-dependent. We’ll look briefly at the last five steps here.

• Creating a Help Text File:

To create a Help Text File, you need to use a word processor capable of saving documents in rich-text format (RTF). Word and WordPerfect do admirable jobs. The Help Text File is basically a list of footnoted topics, with associated topic ID’s. Some general rules of Help Text Files:

o Topics are separated by hard page breaks (no break after last topic!) o Each topic must have a Topic ID. o Each topic can have a title. Once completed, your Help Text File is saved as an RTF (rich text format) file. Make your text file as complete and accurate as possible and please check for misspellings – nothing scares a user more than a poorly prepared help file. They quickly draw the conclusion that if the help system is not built with care, the application must also be sloppily built.

Page 208: VB6 DB Manual

Visual Basic and Databases

© LAP II

ccviii

• Help Text File Example: We’ll create a very simple help text file with three topics. I used Word 2000 in this example. Create a document with the following structure and footnotes:

Note page breaks separate each section. Do not put a page break at the end of the file. Also, note the use of footnotes. The # footnote is used to specify a Topic ID. The footnotes for this example are:

When done, save this file as HelpExample.rtf (Rich Text Format).

Page 209: VB6 DB Manual

Contents

© LAP II

ccix

• Creating the Help Contents File:

The Help Contents File specifies what topics to display when the help system’s Contents tab is selected. This file is created using the Microsoft Help Complier Workshop. Start the Microsoft Help Workshop. Choose the New option under the File menu. Choose Help Contents, then click OK. The following window appears:

Click the top Edit button. For Default Filename, type HelpExample.hlp. For Default Title, type Help Example. Click OK. We’ll now add the three topics. Click Add Below. In the window that appears, type Topic 1 for Title and TOPIC1 for Topic ID. Click OK. Repeat these steps for Topic 2 and Topic 3. When complete, the window should look like this:

Choose Close under the File menu and assign a name of HelpExample.cnt to this contents file.

Page 210: VB6 DB Manual

Visual Basic and Databases

© LAP II

ccx

• Creating the Help Project File:

The Help Project File contains the information required by the Help Compiler to create the Help file. It, too, is created using the Microsoft Help Complier Workshop. Choose the New option under the File menu. Choose Help Project, then click OK. Assign a Project File Name (for this example, use HelpExample). The following window will appear:

We need to specify where our help topic file is located. Click Files, then Add. Locate HelpExample.rtf, then click Open. You will return to the Topic Files window. HelpExample.rtf should be selected. Click OK. The project file is now listed:

Page 211: VB6 DB Manual

Contents

© LAP II

ccxi

• Compiling the Help File:

This is the easiest step. After creating the project file in the Help Compiler Workshop, click the button marked Save and Compile. This saves your listed project file and creates the help file. The created file has the same name as your Help Project File with an HLP extension. Create HelpExample.hlp. You can now exit the Help Compiler Workshop.

• Attaching the Help File:

The final step is to attach the compiled help file to your Visual Basic application. As a first step, open the Project Properties window under the Project menu. Under Help File, select the name of your HLP file by clicking the ellipsis (...). This ties the help file to the application, enabling the user to press <F1> for help. You can also add a Help item to your application using a command button (or some other control) that invokes help via its Click event. If you do this, you must write code to invoke the help file. The code involves a call to the Windows API function, WinHelp. The function declaration (from the API Text Viewer) for WinHelp is:

Declare Function WinHelp Lib "user32" Alias "WinHelpA" (ByVal hwnd As Long, ByVal lpHelpFile As String, ByVal wCommand As Long, ByVal dwData As Long) As Long

We also need a constant:

Const HELP_FINDER = &HB This constant (not in the API Text Viewer, by the way) will display the Help files Contents tab upon invocation of WinHelp. There are other constants that can be used with WinHelp - this is just a simple example.

Page 212: VB6 DB Manual

Visual Basic and Databases

© LAP II

ccxii

The Declare statement and constant definitions usually go in the general declarations area of a code module and made Public. If you only have one form in your application, then put these statements in the General Declarations area of your form (and declare them Private). Once everything is in-place, to invoke the Help file from code, use the function call:

Dim R As Long . . R = WinHelp(myform.hWnd, filename.HLP, HELP_FINDER, CLng(0))

where myform is the name of the project ‘startup’ form and filename is the help file name, including path information (a string variable).

• Help File Example:

We can now try our example help file in a Visual Basic application. We’ll only use the <F1> option here. Start a new application. Bring up the Project Properties window via the Project menu. Select the correct Help File (HelpExample.hlp) by clicking the ellipsis and finding your newly created file. Click OK. Now, run your application (I know there’s nothing in the application, but that’s all right). Once, it’s running press <F1>. This Help screen should appear:

Page 213: VB6 DB Manual

Contents

© LAP II

ccxiii

Double-click Topic 1 and the corresponding Topic 1 screen appears:

Look at the other topics, if you’d like (yeah, I know they’re not real exciting to look at). Click the Find tab and a searchable list of words will be built for your help system. All this power comes free with the Windows help system.

• After all this work, you will still only have a simple help file, nothing that rivals those seen in most applications. But, it is a very adequate help system. To improve your help system, you need to add more features. Investigate the Help Compiler Workshop for suggestions such as context-sensitive help (we’ll use this in the next chapter), graphics, and help macros.

• For Visual Basic 6 users, an additional help building system is available: the

HTML Help Workshop. This new wave of help systems incorporates Internet browser technology for display. You might like to study this system to see the “latest and greatest.”

Page 214: VB6 DB Manual

Visual Basic and Databases

© LAP II

ccxiv

Example 6-8

Authors Table Input Form (On-Line Help Systems) We will build a simple help system for our Authors Table Input Form and attach it to our application. Refer back to the notes to complete each step listed here. 1. Using your word processor, write a Help Text File with a single topic. The

topic and text I used are:

#Authors Input Form Available options for managing Authors database table: Add New Record Click the Add New button to add a record to the Authors database. Type in the Author Name (required), then Year Born (optional). Click Save to save the new record; click Cancel to ignore the new record. Edit Record Click the Edit button to edit the displayed record. Make any needed changes. The Author Name is required and the Year Born is optional. Click Save to save the changes; click Cancel to ignore the changes. Delete Record Click the Delete button to delete the displayed record. Exit Program Click the Done button to quit the application. #Topic1

Establish a topic ID (we used Topic1) footnote for the one topic. Save this file as Authors.rtf.

2. Create a contents file for this example. Name it Authors.cnt.

3. Create a project file for this example. Name it Authors.hpj.

4. Save and compile your help file (named Authors.hlp).

Page 215: VB6 DB Manual

Contents

© LAP II

ccxv

5. Load Example 6-7 completed earlier.

ADO Data Control Modification Load Example6-7AD (the ADO data control version).

ADO Data Environment Modification Load Example6-7DE (the ADO data environment version).

We will modify this example to include our help system. Choose the project Properties option under the Project menu item. Select Authors.hlp as your help file. Save the project. Run it. Press <F1> and the help system should magically appear.

6. Add a command button to the form. Assign a Caption of &Help and a Name

of cmdHelp. The form now looks like this:

Page 216: VB6 DB Manual

Visual Basic and Databases

© LAP II

ccxvi

7. Using the API Text Viewer (we assume you know how to use this – if not, consult the Visual Basic documentation, or on-line help), copy the Declare statement for the WinHelp API function. Place this statement in the General Declarations area (also add the constant HELP_FINDER, which for some reason is not included with the API Text Viewer):

Private Declare Function WinHelp Lib "user32" Alias "WinHelpA" (ByVal hwnd As Long, ByVal lpHelpFile As String, ByVal wCommand As Long, ByVal dwData As Long) As Long Private Const HELP_FINDER = &HB

8. Attach this code to the cmdHelp_Click event procedure:

Private Sub cmdHelp_Click() Dim Rtn As Long Rtn = WinHelp(frmAuthors.hwnd, App.HelpFile, HELP_FINDER, CLng(0)) End Sub

We’ve used the Visual Basic App object here to point to the help file. In Step 5, we set the help file location as a project property. When this is done, Visual Basic saves the path to the help file in the variable App.HelpFile. By not ‘hard-coding’ the help file path in the WinHelp call, no code change is needed if the help file location or name is changed at a later time.

9. Save and run the application. Click Help. You now have two ways to access

your on-line help system.

Page 217: VB6 DB Manual

Contents

© LAP II

ccxvii

Application Testing • Our discussion of Visual Basic interface design has, for now, come to an end.

And, we have a fairly complete interface for the books database Authors table. We, obviously, still need the remainder of the code that goes behind the command buttons. We’ll do that in the next chapter.

• Once you have completed an application, you need to test it to make sure it

performs as expected. If you are careful in building your application, no big surprises should appear in this final testing. In fact, the Visual Basic environment helps achieve this goal. The event-driven nature of Visual Basic makes it easy to build an application in stages, testing and debugging each stage as it is built. In other words, you don’t have to have a complete application before testing can begin. We have done this with the Authors Table example.

• The event-driven nature of Visual Basic also makes it easy to modify an

application. We will see in Chapter 7, as we modify the books database example, that we have made some omissions and errors in our design. But these omissions and errors will be easily corrected using the Visual Basic environment. These corrections will give you additional insight into application building and testing process.

• Let others (particularly potential users) try your application and see if its use is

as obvious as you planned it to be. Are the inputs and outputs of the project appropriate? Is application state clear? Implement and retest any necessary changes, based on user feedback. And, keep track of all feedback after you ‘release’ your application. This information can be used in future updates of your product.

• Before leaving this chapter, let’s look at some other Visual Basic controls that

you might like to use in your database interface arsenal – so-called, custom controls.

Page 218: VB6 DB Manual

Visual Basic and Databases

© LAP II

ccxviiiCustom Controls • In addition to the standard Visual Basic controls discussed earlier in this

chapter, there are many custom controls that can be used to build a database interface. These controls must be added to the Visual Basic toolbox before they can be used. In most cases, there are separate sets of custom controls, depending on whether you are using DAO or ADO data access.

• To load a custom control, choose Components from the Visual Basic Project

menu. The Components (custom control) dialog box is displayed (make sure the Controls tab is selected):

To add a control or controls, select the check box next to the desired selection(s). When done, choose OK and the selected control(s) will now appear in the toolbox. Each custom control has its own set of properties, events, and methods. The Visual Basic on-line help system can provide details for usage.

• Here, we look at several custom controls (some data bound, some not) and

how they can be used with a Visual Basic interface. Several examples using the DAO versions of the controls will be provided.

Page 219: VB6 DB Manual

Contents

© LAP II

ccxix

Masked Edit Control

• The masked edit control is a data bound control used to prompt users for data input using a mask pattern. It works like a text box, but the mask allows you to specify exactly the desired input format. In a database, this control could be used to prompt for a date, a time, number, or currency value. Or it could be used to prompt for something that follows a pattern, like a phone number or social security number. Use of this control can eliminate many of the entry validation problems mentioned earlier in the chapter. To load this control, select Components from the Projects menu, then select from the Components dialog box:

DAO/ADO Version Microsoft Masked Edit Control

• Masked Edit Properties:

DataField Field in database table, specified by DataSource (or DataMember), bound to masked edit control (DAO or ADO).

DataMember Specifies the Command object establishing the database table (ADO data environment only).

DataSource Specifies the data control (DAO or ADO) or data environment (ADO) the masked edit control is bound to.

Mask Determines the type of information that is input into the control. It uses characters to define the type of input. Check on-line help for mask formatting.

PromptInclude If True, prompt characters included with Text property. Text Contains data entered into the control (including all prompt

characters of the input mask). This is the property bound to the database.

• Masked Edit Events:

Change Event called when the data in the control changes. Validation Error Event called when the data being entered by the user does

not match the input mask. • This control features built-in input validation to lessen your tasks as a

programmer. We will use the masked edit control in some of our example applications in later chapters.

Page 220: VB6 DB Manual

Visual Basic and Databases

© LAP II

ccxx

Quick Example 1 - Masked Edit Control 1. We’ll use the masked edit control to input a phone number. Start a new

project. Add a masked edit control to the toolbox. Place a masked edit control and text box on your form.

2. Set the masked edit control Mask property to: (###) ###-####. This mask will

allow an area code, followed by a phone number. Your form should look like this:

3. Place this code in the MaskEdBox1_Change event:

Private Sub MaskEdBox1_Change() Text1.Text = MaskEdBox1.Text End Sub

4. Save the application and run it. Notice how simple it is to fill in a correct phone

number. The text box reflects what is typed in the masked edit control. The Text property of the masked edit control is bound to the database. Change the PromptInclude property to False and note the prompt characters (parentheses, hyphen) are not included in the Text property.

Page 221: VB6 DB Manual

Contents

© LAP II

ccxxi

UpDown Control

• The UpDown control is a pair of arrow buttons that the user can click to

increment or decrement a value. It works with a buddy control that uses the UpDown control’s Value property. It is used in databases to select from a relatively small (less than 30 or so) list of items. To load this control, select Components from the Projects menu, then select from the Components dialog box:

DAO Version Microsoft Windows Common Controls-2 5.0 ADO Version Microsoft Windows Common Controls-2 6.0

Several other controls are loaded with this group.

• UpDown Control Properties:

BuddyControl Name of buddy control BuddyProperty Property in buddy control established by Value property of

UpDown control. Max Establishes upper limit for value property. Min Establishes lower limit for value property. Increment Amount control value changes each time an arrow is

clicked. Orientation Determines whether arrows lie horizontally or vertically. Value Current control value.

• UpDown Control Events:

Change Invoked when value property changes. UpClick Invoked when up arrow is clicked. DownClick Invoked when down arrow is clicked.

• The UpDown control is a ‘point-and-click’ type control that can be used in

place of a user’s typed input. We will use the UpDown control in some of our example applications in later chapters.

Page 222: VB6 DB Manual

Visual Basic and Databases

© LAP II

ccxxii

Quick Example 2 - UpDown Control 1. We can use two UpDown controls to input a user’s birthdate. Start a new

application. Add the UpDown control to the toolbox. Place two UpDown controls and two label controls on the form.

2. Set these properties for the UpDown controls (UpDown1 will set the birth

month, UpDown2 will set the day):

UpDown1: Min 1 Max 12 Value 1

UpDown2: BuddyControl Label2 BuddyProperty Caption Value 1 Min 1 Max 31 Value 1

The form should look something like this:

3. Add these lines to the General Declarations area:

Option Explicit Dim Month(12) As String

Page 223: VB6 DB Manual

Contents

© LAP II

ccxxiii

4. Add this code to the Form_Load event (to name the months):

Private Sub Form_Load() Month(1) = "January": Month(2) = "February" Month(3) = "March": Month(4) = "April" Month(5) = "May": Month(6) = "June" Month(7) = "July": Month(8) = "August" Month(9) = "September": Month(10) = "October" Month(11) = "November": Month(12) = "December" Label1.Caption = Month(1) Label2.Caption = "1" End Sub

5. Add this code to the UpDown1_Change event:

Private Sub UpDown1_Change() Label1.Caption = Month(UpDown1.Value) End Sub

6. Save the application. Run the application. Birthdates (or any date for that

matter) are now easy to input. Can you think of an additional validation you would need (Hint - 30 days has September, April, June and November ...)?

Page 224: VB6 DB Manual

Visual Basic and Databases

© LAP II

ccxxivTabbed Dialog Control

• The tabbed dialog control provides an easy way to present several dialogs or

screens of information on a single form using the same interface seen in many commercial Windows applications. To load this control, select Components from the Projects menu, then select from the Components dialog box (notice this itself is a tabbed dialog control!):

DAO/ADO Version Microsoft Tabbed Dialog Control

• The tabbed dialog control provides a group of tabs, each of which acts as a

container (works just like a frame or separate form) for other controls. Only one tab can be active at a time. Using this control is easy. Just build each tab container as a separate mini-application: add controls, set properties, and write code like you do for any application. Navigation from one container to the next is simple: just click on the corresponding tab.

• Tabbed Dialog Control Properties:

Caption Title information on ‘folder’ tab TabOrientation Determines where the ‘folder’ tabs are positioned. Tabs Total number of displayed tabs. TabsPerRow Number of tabs in single row.

• Tabbed Dialog Control Event:

Click Invoked when folder tab is clicked (allows you to determine

which tab is active). • The tabbed dialog control is becoming a very popular control in Windows

applications. It allows you to put a lot of ‘input power’ into a single form - minimizing the need for multi-form applications. We will use the tabbed dialog control in some of our example applications in later chapters.

Page 225: VB6 DB Manual

Contents

© LAP II

ccxxv

Quick Example 3 - Tabbed Dialog Control 1. Start a new application. Add the tabbed dialog control to the toolbox. Put a

tabbed dialog control on the form:

Play with the various properties to see how different styles and layouts appear on the form.

2. Design each tab with some controls, then run the application. Note how each

tab in the folder has its own working space.

Page 226: VB6 DB Manual

Visual Basic and Databases

© LAP II

ccxxviToolbar Control

• Almost all Windows applications these days use toolbars. A toolbar provides

quick graphical access (by clicking a picture) to the most frequently used commands in an application. In a database application, it could be used to add, delete, or edit records. It could be used to access database reports or obtain different database views. The toolbar control is a mini-application in itself. It provides everything you need to design and implement a toolbar into your application. To load this control, select Components from the Projects menu, then select from the Components dialog box:

DAO Version Microsoft Windows Common Controls 5.0 ADO Version Microsoft Windows Common Controls 6.0

Several other controls are loaded with this group.

• To create a basic toolbar, you need to follow a sequence of steps. You

add buttons to a Button collection - each button can have optional text and/or an image, supplied by an associated ImageList control (another custom control). Buttons can have tooltips. In more advanced applications, you can even allow your user to customize the toolbar to their liking!

• Toolbar Control Properties:

Align Establishes location of toolbar (usually at top of form). ButtonHeight Height of buttons on toolbar. ButtonWidth Width of buttons on toolbar. ImageList ImageList control containing pictures that appear on the

toolbar (images are bitmap files). Key Keyword used to identify button (used to determine which

button is clicked). ShowTips If True, tooltips appear as to what a particular button’s

function is. • Toolbar Control Event:

ButtonClick Invoked when one of the toolbar buttons is clicked.

Page 227: VB6 DB Manual

Contents

© LAP II

ccxxvii

Quick Example 4 - Toolbar Control 1. We’ll look at the simplest use of the toolbar control - building a fixed

format toolbar (pictures only) at design time. We’ll create a toolbar that replicates the function of the five command buttons used in Example 6-2: one to add a new record, one to save a record, one to cancel an edit, one to edit a record, and one to delete a record. Start a new project. Add the toolbar control to the toolbox. Place a toolbar, an imagelist control, and a label control on the form.

2. Right click on the image list control to set the pictures to be used.

Using the Images tab, assign the following five images (click Insert Picture, then select graphic). The needed files are included with the course example code.

Image 1 - NEW.BMP Image 2 - SAVE.BMP Image 3 - CANCEL.BMP Image 4 - EDIT.BMP Image 5 - DELETE.BMP

When done, the image control should look like this:

Click OK to close this box.

Page 228: VB6 DB Manual

Visual Basic and Databases

© LAP II

ccxxviii3. Right mouse click on the toolbar control. The Property Pages dialog

box will appear. Using the General tab, select the image list control (ImageList1) just formed. Now, choose the Buttons tab to define each button. A new button is added to the toolbar by clicking Insert Button. At a minimum, for each button, specify the Key (used to identify which button is clicked), ToolTipText property, and the Image number. Values I used are:

Index Key ToolTipText Image

1 New Add New Record 1 2 Save Save Record 2 3 Cancel Cancel 3 4 Edit Edit Record 4 5 Delete Delete Record 5

When done, my form looks like this:

4. Add this code to the Toolbar1_ButtonClick event:

Private Sub Toolbar1_ButtonClick(ByVal Button As ComctlLib.Button) Label1.Caption = Button.Key + " Clicked" End Sub

5. Save and run the application. Click a button on the toolbar - the label control

specifies which button was clicked. Check out how the tool tips work (hold the cursor over a button for a bit). The toolbar is a very powerful and professional tool. And, it’s easy to implement and use. Try to use it whenever it fits the design of your interface.

Page 229: VB6 DB Manual

Contents

© LAP II

ccxxix

Data Bound List Control

• The data bound list control allows you to display multiple rows of data in the same control, giving you a ‘pick list’ of values. It is automatically filled with a field from a specified data control. Selections from the list box can then be used to update another field from the same data control or, optionally, used to update a field from another data control. Note this is not the same as the standard list control, which is not data bound. To load this control, select Components from the Projects menu, then select from the Components dialog box:

DAO Version Microsoft Data Bound List Controls ADO Version Microsoft DataList Controls

• Data Bound List Control Properties:

BoundColumn Name of field in Recordset specified by RowSource to be

passed to DataField, once selection is made. BoundText Text value of BoundColumn field. This is the value passed

to DataField property. DataField Name of field in table specified by DataSource (or

DataMember) updated by selection. DataSource Name of data control (DAO or ADO) or data environment

(ADO) that is updated by the selection. DataMember Specifies the Command object establishing the table

updated by the selection (ADO data environment only). ListField Name of field in table specified by RowSource (or

RowMember) used to fill list box. RowMember Specifies the Command object establishing the table used

by ListField (ADO data environment only). RowSource Name of data control (DAO or ADO) or data environment

(ADO) used as source of items in list box. Text Text value of selected item in list.

• Data Bound List Control Event: Click Invoked when item in list control is clicked.

Page 230: VB6 DB Manual

Visual Basic and Databases

© LAP II

ccxxx

• One use for the data bound list control is to fill the list (ListField) from the database (RowSource), then allow selections. This allows us to list all values of a particular field in a database recordset. The selections can be used by any control on a form, whether it is data bound or not.

• A powerful feature of the data bound list control is linking to (and updating)

other fields in a database. This involves setting three more properties (DataSource, DataField, and BoundColumn). Here’s the logic: RowSource is set to the data control establishing the recordset providing the information listed (ListField) in the list box. This establishes the source table. BoundColumn is the field name from the source table record used as a link. DataSource is the recordset linked by the BoundColumn (it can be the same recordset as RowSource or another recordset). Then, DataField is the field in DataSource that is linked by BoundColumn.

• The linking property of the data bound list box is widely used when adding to or

updating database records. As an example, say you build a form to add books to the BIBLIO.MDB database. A new book arrives, but you don’t know that particular book publisher’s identification (PubID), but you do know the publisher’s name. To solve this problem, you use a data bound list box with Publisher names. When you pick a name from the list, you have the application find the PubID using the linking capabilities of the list box control. You are essentially hiding the key values (primary and foreign keys) of the database from the user and allowing the user to access information familiar to them, such as the publisher’s name. Let’s build this example in stages.

Page 231: VB6 DB Manual

Contents

© LAP II

ccxxxi

Quick Example 5 - Data Bound List Control 1. Start a new project. Add the data bound list control to the toolbox. Add a DAO

data control and a data bound list control to the form. 2. Set these properties for the data control and list control:

Data1: DatabaseName BIBLIO.MDB RecordSource Publishers ReadOnly True (to save us from mistakes) DBList1:

RowSource datPublishers ListField Company Name

3. Save the application and run it. You should see this:

We have filled the list box with the Company Name field (ListField) from the Publishers database table (RowSource), simply by setting two properties!

4. Add a text box to the form. Set the BoundColumn property to PubID (this

creates an output value based on the selected item in the list box). Add this code to the DBList1_Click event:

Private Sub DBList1_Click() Text1.Text = DBList1.BoundText End Sub

Page 232: VB6 DB Manual

Visual Basic and Databases

© LAP II

ccxxxii5. Save and run the application. Now, click on a publisher name in the list box

and the corresponding PubID value will appear in the text box:

6. We now take this example one step further. We use the data produced by the

BoundText property to link to a field in a separate database table. Recall the Titles table of the BIBLIO.MDB database lists a PubID field, but no publisher name information. We can link PubID in the Titles table with the Company Name field in the Publishers table by modifying this example. Add a second DAO data control - set it’s properties to:

Data2:

DatabaseName BIBLIO.MDB RecordSource Titles ReadOnly True (to save us from mistakes)

Set the data bound list control’s DataSource property to Data2 and the DataField property to PubID.

7. Save and run the application. Click the Data2 data control navigation arrows to

move from record to record in the Titles table. Notice the corresponding publisher name is highlighted in the list control and its PubID appears in the text box. Try adding a bound text box to also list the corresponding book title as you are navigating.

Page 233: VB6 DB Manual

Contents

© LAP II

ccxxxiii

Data Bound Combo Control

• The data bound combo control is nearly identical to the data bound list box, hence we won’t look at a separate set of properties or another example. A primary difference between the two controls is the way data is displayed – the combo control has a list box portion and a text box portion that displays the selected item. And, with the combo control, the user is (optionally) given the opportunity to type in a choice not in the list box. To load this control, select Components from the Projects menu, then select from the Components dialog box:

DAO Version Microsoft Data Bound List Controls ADO Version Microsoft DataList Controls

• As mentioned, data display is different with the combo control. Display is

established by the Style property:

Style Symbolic Constant Description 0 VbComboDropDown Drop-down list box, user can change

selection 1 VbComboSimple Displayed list box, user can change

selection 2 vbComboDropDownList Drop-down list box, user cannot change

selection

When using Style = 1, make sure you sufficiently size the control (so the list box portion appears) when it is placed on the form.

• When should you use the combo control instead of the list box control? The

data bound combo control is an excellent data entry control. Its advantage over the list box is that it provides experienced users the ability to type in values they know are correct, speeding up the data entry process. The list box control does not allow any typing. It is also a good control when you are short on form space. Using Style = 2 replicates the functionality of the list box control without needing space for the list box.

Page 234: VB6 DB Manual

Visual Basic and Databases

© LAP II

ccxxxivData Bound Grid Control

• The data bound grid control tool is one of the most useful data bound controls. It can display an entire database table, referenced by a data control. The table can then be edited as desired. To load this control, select Components from the Projects menu, then select from the Components dialog box:

DAO Version Microsoft Data Bound Grid Control ADO Version Microsoft DataGrid Control 6.0

• The data bound grid control is in a class by itself, when considering its

capabilities. It is essentially a separate, highly functional program. It has two primary properties:

DataMember Specifies the Command object establishing the database

table (ADO data environment only). DataSource Name of data control (DAO or ADO) or data environment

(ADO) grid control is bound to. • The data bound grid control is a collection of Column objects, corresponding to

fields in the table, and rows, corresponding to records. Cells can be accessed and edited via mouse operations or programmatically.

• The data bound grid control allows you to monitor editing activities via several

events:

BeforeInsert Occurs before a new row is inserted in the grid. Use to confirm addition of new record.

AfterInsert Occurs after a new row is inserted in the grid. BeforeUpdate Occurs before changes are written to data control. Use to

perform data validation. AfterUpdate Occurs after changes are written to data control. BeforeDelete Occurs before selected record(s) are deleted. Use to

confirm deletion. AfterDelete Occurs after selected record(s) are deleted.

• You are encouraged to further study the data bound grid control (properties,

events, methods) as you progress in your database studies. We will use it in applications studied in later chapters.

Page 235: VB6 DB Manual

Contents

© LAP II

ccxxxv

Quick Example 6 – Data Bound Grid Control 1. Start a new project. Add a data control and a data bound grid control. Set

these properties:

Data1: DatabaseName BIBLIO.MDB RecordSource Titles ReadOnly True

DBGrid1:

DataSource Data1

2. Save and run the application. The following will appear:

At this point, we can scroll through the table and edit any values we choose. Any changes are automatically reflected in the underlying database. Column widths can be changed at run-time! Multiple row and column selections are possible! Like we said, a very powerful tool.

Page 236: VB6 DB Manual

Visual Basic and Databases

© LAP II

ccxxxviData Bound FlexGrid Control

• The data bound grid control is an excellent tool for providing full-editing

features in a spreadsheet like fashion. However, it is memory intensive and not real fast. If you only need display capabilities (no editing), consider the data bound flexgrid control. This control offers an amazing array of variations in how data can be displayed. To load this control, select Components from the Projects menu, then select from the Components dialog:

DAO/ADO Version Microsoft FlexGrid Control

• Display of data in the flexgrid control is established by two properties:

DataMember Specifies the Command object establishing the database table (ADO data environment only).

DataSource Name of data control (DAO or ADO) or data environment (ADO) grid control is bound to.

• The flexgrid control offers a wide number of properties that allows you to

display the data in any format you desire. You can change the color and style of nearly every piece of information in the grid (gridlines, fonts, colors, selections, …). Examine the on-line help file for this control to enhance your knowledge of these properties.

Page 237: VB6 DB Manual

Contents

© LAP II

ccxxxvii

Quick Example 7 – Data Bound FlexGrid Control 1. Start a new project. Add a data control and a data bound flexgrid control. Set

these properties:

Data1: DatabaseName BIBLIO.MDB RecordSource Titles ReadOnly True

MSFlexGrid1:

AllowUserResizing 1 - flexResizeColumn DataSource Data1 FixedCols 0 (we only want data columns displayed)

2. Save and run the application. The following will appear:

All records (with columns labeled) from the Titles table appear. Notice you can only view the data – no editing is possible.

Page 238: VB6 DB Manual

Visual Basic and Databases

© LAP II

ccxxxviiiCalendar Control

• The calendar control is a tool for displaying and determining dates. It

provides a simple to use interface to display any monthly calendar and select a date. To load this control, select Components from the Projects menu, then select from the Components dialog:

DAO/ADO Version Microsoft Calendar Control

• Calendar Control Properties:

DataField Field in database table, specified by DataSource (or DataMember), bound to calendar control (DAO or ADO).

DataMember Specifies the Command object establishing the database table (ADO data environment only).

DataSource Specifies the data control (DAO or ADO) or data environment (ADO) the calendar control is bound to.

Day The number (1-31) of the currently selected day. Month The number (1-12) of the currently selected month. Value The value of the selected date (property bound to data

control or data environment). This is set to the current date by default.

Year The number of the currently selected year. • Calendar Control Event:

Click Invoked when user clicks on a date in the calendar control.

Page 239: VB6 DB Manual

Contents

© LAP II

ccxxxix

Quick Example 8 – Calendar Control The books database we have been using throughout this chapter does not have a field with dates. Hence, here (and in some later examples needing dates and plotting values) we use the Northwind Traders database used at the end of previous chapters. This database (NWIND.MDB), like BIBLIO.MDB, ships with Visual Basic. If you have not already done so, move a copy of this file it to your working directory. 1. Start a new application. Add the calendar control a DAO data control to your

toolbox. Now add a calendar control, the data control, and a label control to your form. It should look like this:

2. Set these properties:

Data1: DatabaseName NWIND.MDB (point to working copy) RecordSource Orders

Calendar1:

DataSource Data1 DataField OrderDate

Label1:

DataSource Data1 DataField OrderDate

3. Save and run the application. Click the data control to move through the

records of the Orders table. As you do, the Order Date will be shown on both the calendar control and in the label control.

Page 240: VB6 DB Manual

Visual Basic and Databases

© LAP II

ccxl

Common Dialog Control

• In all examples studied in this course, the database name has been assumed

to be known at design time (before running the application). There will be times when this is not true. For example, say a schoolteacher uses a database application to keep track of grades. There will database files for each class. When the teacher starts the application, he or she needs to specify which particular database file is being accessed and that file needs to be opened at run-time. Not only do we need the capability to open a user specified file, but we also need to be able to save database files with user specified names. At this point, we will not address how to open or save databases at run-time. This will be discussed in later chapters. As part of our discussion of custom controls, however, we will address how to get user specified file information.

• What we need from the user, whether opening or saving files, is a complete

path to the filename of interest. We could provide a text box and ask the user to type the path, but that’s only asking for trouble. We would have to validate existence of drives, directories, and files! Fortunately, we can use the Windows standard interface for working with files. Visual Basic provides this interface through the common dialog control. This control displays the same interface you see when opening or saving a file in any Windows application. Such an interface is familiar to any Windows user and gives your application a professional look. And, some context-sensitive help is available while the interface is displayed.

• Like other custom controls, if the common dialog control does not appear in the

Visual Basic toolbox, you need to add it. To load this control, select Components from the Projects menu, then select from the Components dialog:

DAO/ADO Version Microsoft Common Dialog Control

• The common dialog control, although it appears on your form, is invisible at

run-time. The control is used to display a dialog box using a Show method. For a common dialog box named cdlExample, to see the Open dialog box, use:

cdlExample.ShowOpen

Page 241: VB6 DB Manual

Contents

© LAP II

ccxli

To see the Save As dialog box, use:

cdlExample.ShowSave

You cannot control where the common dialog box appears on your screen. Once the dialog box is closed in some manner, control to the program returns to the line immediately following this line. Common dialog boxes are system modal.

• Common Dialog Control Properties:

CancelError If True, generates an error if the Cancel button is clicked. Allows you to use error-handling procedures to recognize that Cancel was clicked.

DefaultExt Sets the default extension of a file name if a file is listed without an extension.

DialogTitle The string appearing in the title bar of the dialog box.

FileName File name that appears in the File name box. Filter Used to restrict the filenames that appear in the file

list box. FilterIndex Indicates which filter component is default. Flags Values that control special features of the common

dialog control. • The Flags property is an especially important one. Using proper values can

insure any file name provided by the user is a valid one. For opening files with a common dialog control named cdlExample, we suggest:

cdlExample.Flags = cdlOFNFileMustExist + cdlOFNPathMustExist

These values on the right are Visual Basic constants that insure both the specified file and path exist before trying to open it. For saving files, use:

cdlExample.Flags = cdlOFNOverwritePrompt + cdlOFNPathMustExist

The constants here will insure files are not overwritten without user concurrence and that any specified path must exist.

Page 242: VB6 DB Manual

Visual Basic and Databases

© LAP II

ccxlii

Quick Example 9 – Common Dialog Control 1. Start a new project. Add a common dialog control (set CancelError to True),

two command buttons and a label control:

2. Attach the following code to the Command1_Click event procedure:

Private Sub Command1_Click() CommonDialog1.Flags = cdlOFNFileMustExist + cdlOFNPathMustExist On Error GoTo CancelPressed CommonDialog1.ShowOpen Label1.Caption = CommonDialog1.filename Exit Sub CancelPressed: Label1.Caption = "Cancel Pressed" Exit Sub End Sub

This code will display the Open dialog box when the command button is clicked. Note the use of error trapping to determine if Cancel is clicked.

3. Attach the following code to the Command2_Click event procedure:

Private Sub Command2_Click() CommonDialog1.Flags = cdlOFNOverwritePrompt + cdlOFNPathMustExist On Error GoTo CancelPressed CommonDialog1.ShowSave Label1.Caption = CommonDialog1.filename Exit Sub CancelPressed: Label1.Caption = "Cancel Pressed" Exit Sub End Sub

This code will display the Save dialog box when the command button is clicked.

Page 243: VB6 DB Manual

Contents

© LAP II

ccxliii

4. Save the application and run it. Click Command1. The Open dialog box appears. Type in garbage for a filename. Click Open. The filename will not be accepted. Type (or select) a valid name. Click Open. The complete path to the file will be displayed in the label control. We would use this name to open a database file. Click Command1 again and make sure Cancel works.

5. Click Command2. The Save dialog box appears. Type in garbage for a file

path. Click Save. The entry will not be accepted. Type in (or select) an existing filename. You will be asked if you want to overwrite the file. Answer No (even though there is no possibility of overwriting – we have no code to do such). Type (or select) a valid name. Click Save. The complete path to the file will be displayed in the label control. We would use this name to save a database file. Click Command2 again and make sure Cancel works.

Page 244: VB6 DB Manual

Visual Basic and Databases

© LAP II

ccxliv

Additional ADO Custom Controls • The introduction of Visual Basic 6 brought several new custom controls that

can be of use to us in our database applications. These controls only work with the ADO data control and ADO data environment discussed in Chapter 4.

• Here, we look at several ADO custom controls (some data bound, some not)

and how they can be used with a Visual Basic interface. Several examples using the ADO data control will be provided.

Hierarchical FlexGrid Control

• The hierarchical flexgrid control is a new version of the flexgrid control

studied earlier. It features the ability to merge, sort, and format data tables. The displayed data still cannot be edited. However, entire rows can be selected, range selections (like Excel spreadsheets) can be made, and ‘drag and drop’ of cells is possible. To load this control, select Components from the Projects menu, and then select Microsoft Hierarchical FlexGrid Control 6.0.

• Display of data in the hierarchical flexgrid control is established by two

properties:

DataMember Specifies the Command object establishing the database table (ADO data environment only).

DataSource Name of data control (DAO or ADO) or data environment (ADO) grid control is bound to.

• The hierarchical capabilities of this control require creation of hierarchical

recordsets that are somewhat complicated. We will not address such recordsets here. We will, however, develop an example that illustrates some of the merging power of the control.

Page 245: VB6 DB Manual

Contents

© LAP II

ccxlv

Quick Example 10 – Hierarchical FlexGrid Control 1. Start a new application. Add a hierarchical flexgrid control and an ADO data

control to the form. Both of these controls will need to be added to your toolbox. Set these properties:

Adodc1:

ConnectionString BIBLIO.MDB (point to working copy) CommandType 2-adCmdTable RecordSource Titles

MSHFlexGrid1:

DataSource Adodc1 2. Right-click the flexgrid control and click Retrieve Structure. This control

allows you to see the table structure at design time (not possible with the old flexgrid control). Right-click again and choose Properties. Make the General tab active. Set Fixed Cols to 0 (to eliminate the blank column at the left). Set AllowUserResizing to 1-Columns.

3. Click the Bands tab. We want to merge fields. The first column is used for

merging. We want it to be a key, PubID. Select PubID in Column Caption, then click the Up arrow until that field moves to the top of the list. PubID should now be the first field listed:

Page 246: VB6 DB Manual

Visual Basic and Databases

© LAP II

ccxlvi

4. We need some code to do the merge. Here it is (don’t get to worried if this isn’t obvious) – it goes in the Form_Activate event:

Private Sub Form_Activate() Dim I As Integer MSHFlexGrid1.Row = 0 For I = 0 To MSHFlexGrid1.Cols - 1 MSHFlexGrid1.Col = I MSHFlexGrid1.CellAlignment = 4 MSHFlexGrid1.MergeCol(I) = True Next I MSHFlexGrid1.Col = 0 MSHFlexGrid1.ColSel = MSHFlexGrid1.Cols - 1 MSHFlexGrid1.Sort = flexSortGenericAscending MSHFlexGrid1.MergeCells = flexMergeRestrictColumns End Sub

This code sets the alignment (right justified) on all the columns and makes them ‘mergeable.’ The last line tells cells to merge if they match cells above (in this case, all records with the same PubID will merge.

5. Save the application and run it. You should see:

All the publishers are now grouped. Not bad for just a few lines of code.

Page 247: VB6 DB Manual

Contents

© LAP II

ccxlvii

Chart Control

• The chart control is an amazing tool. In fact, it’s like a complete program in

itself. It allows you to design all types of graphs interactively on your form. Then, at run-time, draw graphs, print them, copy them, and change their styles. To load this control, select Components from the Projects menu, and then select Microsoft Chart Control 6.0.

• Chart Control Properties:

Column Returns or sets the current column in the grid of data being charted.

ChartType Establishes the type of chart to display. Data Returns or sets the data in the current row and

column of the grid of data being charted. DataMember Specifies the Command object establishing the database

table (ADO data environment only). DataSource Specifies the data control or data environment the chart

control is bound to. RandomFill Used to fill chart with random values (good for

checking out chart at design-time). Data is normally filled from established array.

Row Returns or sets the current row in the grid of data being charted.

Visual Basic 5 users might be asking: isn’t there a Chart control we can use with the DAO data control? Yes, but it is not data bound and requires programmatic storing of data for plotting. It is a straightforward task, but will not be addressed here. The non-bound control will be used in Chapter 11 in an example.

• The chart control is valuable. It allows a user a quick overview of any

numerical data within a database. We will use it in some of our later applications.

Page 248: VB6 DB Manual

Visual Basic and Databases

© LAP II

ccxlviiiQuick Example 11 – Chart Control Like an earlier example, this example uses the Northwind Traders database to have a value for charting. 1. Start a new project. Add a chart control (make sure it is the Visual Basic 6

version) and ADO data control to the form. Set these properties:

Adodc1: ConnectionString NWIND.MDB (point to working copy) CommandType 1-adCmdText RecordSource SELECT ProductName, UnitPrice FROM Products

WHERE SupplierID < 5

MSChart1: DataSource Adodc1

We restrict the SupplierID value to limit the number of records returned.

2. Save the application, then run it. A bar chart of UnitPrice versus ProductName

should appear:

Magic, huh? If all the labels don’t appear in your example, you need to enlarge the size of the control on your form.

Page 249: VB6 DB Manual

Contents

© LAP II

ccxlix

Month View Control

• A common need for a database field is a properly formatted date or time. We

could allow the user to type the information in a text box, but we know that is asking for trouble (remember the validations needed for typed input). Visual Basic offers several data bound date entry tools. We look at the first of three here: the month view control. This control provides a clickable calendar that lets users view and set date information. Single dates or date ranges may be selected. Up to 12 months at a time can be displayed. To load this control, select Components from the Projects menu, and then select Microsoft Windows Common Controls-2 6.0.

• Month View Control Properties:

DataField Field in database table, specified by DataSource (or DataMember), bound to month view control.

DataMember Specifies the Command object establishing the database table (data environment only).

DataSource Specifies the data control or data environment the month view control is bound to.

DateClicked Date value clicked in DateClick event. Day The number (1-31) of the currently selected day. Month The number (1-12) of the currently selected month. Value The value of the selected date (property bound to data

control or data environment). This is set to the current date by default.

Week The number (1-52) of the currently selected week. Year The number of the currently selected year.

• Month View Control Event:

DateClick Invoked when user clicks on a date in the month view control.

• This control has many more properties for multiple month displays, multiple

date selections, and appearance, that you might like to investigate. The month view control will be used in some of our later examples.

Page 250: VB6 DB Manual

Visual Basic and Databases

© LAP II

ccl

Quick Example 12 – Month View Control 1. Start a new application. Add the month view control and ADO data control to

your toolbox. Now add a month view control, the data control, and a label control to your form. It should look like this (note the current month will display – you now know when this was being written):

2. Set these properties:

Adodc1: ConnectionString NWIND.MDB (point to working copy) CommandType 2-adCmdTable RecordSource Orders

MonthView1:

DataSource Adodc1 DataField OrderDate

Label1:

DataSource Adodc1 DataField OrderDate

3. Save and run the application. Click the data control to move through the

records of the Orders table. As you do, the Order Date will be shown on both the month view control and in the label control. Notice you can change the displayed month using the arrows at the top (or try the standard cursor control keys). If you click a new date, then move off that record using the data control, that date becomes the new order date (field is automatically updated). Try it if you like, recognizing you are changing the database.

Page 251: VB6 DB Manual

Contents

© LAP II

ccli

Date Time Picker Control

• The date time picker control is related to the month view control and shares

most of the same properties. The difference here is that the selected date appears in a masked edit control and the calendar portion works in dropdown mode. The returned value can be formatted in many ways.

• Date Time Picker Control Properties (in addition to those given previously for

the month view control):

CheckBox Specifies whether control returns a date (allows optional use of control).

CustomFormat Formatting string that determines how date and/or time will be displayed.

Format Determines how date and/or time will be displayed. You can choose a predefined option or use the custom format feature.

UpDown Determines control mode. When False, operates in Dropdown Calendar Mode (default). When True, user can increment or decrement displayed value using UpDown control (Time Format Mode).

Page 252: VB6 DB Manual

Visual Basic and Databases

© LAP II

cclii

Quick Example 13 – Date Time Picker Control 1. Start a new application. Add the date time picker control and ADO data control

to your toolbox. Now add a date time picker control, the data control, and a label control to your form. It should look like this:

2. Set these properties:

Adodc1: ConnectionString NWIND.MDB (point to working copy) CommandType 2-adCmdTable RecordSource Orders

DTPicker1:

DataSource Adodc1 DataField OrderDate Format 3-dtpCustom CustomFormat 'Order Date is:'MMMMdd', 'yyy'' (these are all single

quotes in this string)

Label1: DataSource Adodc1 DataField OrderDate

3. Save and run the application. Click the data control to move through the

records of the Orders table. As you do, the Order Date will be shown in the date time picker control and in the label control. Play with some of the other features if you like.

Page 253: VB6 DB Manual

Contents

© LAP II

ccliii

Data Repeater Control

• The data repeater control allows you to display more than one database

record at a time, without using a grid type control. You decide how you want to display each record by building your own Visual Basic control! The data repeater then hosts this new control (displayed in the Visual Basic toolbox like all other controls), displaying several instances in a Visual Basic application. To load this control, select Components from the Projects menu, and then select Microsoft DataRepeater Control.

• To use the data repeater control requires a bit of work, but it is worth it. There

are four steps: (1) build the ActiveX control to display the database record, (2) expose properties in the ActiveX control, (3) compile the ActiveX control and (4) bind the ActiveX control to the data repeater control. Rather than discuss these steps in general, we will build an example using the Publishers table from the books database. This is, by far, the best way to illustrate how this powerful control is used.

Page 254: VB6 DB Manual

Visual Basic and Databases

© LAP II

ccliv

Example 6-9

Data Repeater Control In this example, we will use the data repeater control to display multiple publisher names and phone numbers (a ‘computer Rolodex’). This information will come from the Publishers table of the BIBLIO.MDB database. This example will follow the four steps just outlined: (1) build the ActiveX control that displays the record, (2) expose the ActiveX control properties, (3) compile the ActiveX control, and (4) bind the ActiveX control to the data repeater control. Build an ActiveX Control Building an ActiveX control is not any harder than building a Visual Basic application. We build the control, compile it, and register it in the Windows registry. The control we build here will contain two pieces of information from the Publishers table of BIBLIO.MDB – the Company Name field and the Telephone field. 1. Start a new Visual Basic project. In the New Project window, select ActiveX

Control. Select the Project menu item and choose Project Properties. In this window, assign a Project Name of vbdbPublisher. This name will be used as a prefix for the compiled control.

2. Place two label controls and two text boxes on the user control form. Assign

these properties:

UserControl1: Name ctlPublisher

Label1:

Caption Publisher Text1:

Name txtPublisher Label2:

Caption Phone Number Text1:

Name txtPhone

Page 255: VB6 DB Manual

Contents

© LAP II

cclv

Resize the control form so it just fits the space. My form looks like this:

3. Save the control (ctlPublisher.ctl) and project (vbdbPublisher.vbp) to make

sure you don’t lose anything. Expose ActiveX Control Properties We need to add code to our ActiveX control to make the text box controls Text properties available for database binding within the data repeater control. We need to make it possible to both read and set these properties. 1. Open the form code window. Under Tools menu, select Add Procedure. Set

Type to Property, Scope to Public, Name to PublisherName. Repeat these steps to create a Property named PublisherPhone.

2. The previous steps created the code structures that allow us to read (Property

Get statements) and set (Property Let statements) property values. The code for these structures is:

Public Property Get PublisherName() As String PublisherName = txtPublisher.Text End Property Public Property Let PublisherName(ByVal vNewValue As String) txtPublisher.Text = vNewValue End Property Public Property Get PublisherPhone() As String PublisherPhone = txtPhone.Text End Property Public Property Let PublisherPhone(ByVal vNewValue As String) txtPhone.Text = vNewValue End Property

Page 256: VB6 DB Manual

Visual Basic and Databases

© LAP II

cclvi

This code is pretty obvious – it just makes sure proper values are available. One thing to note: by default, all arguments and returned values are defined to be Variant. Make sure, in this example, you change all these default types to String (our property types).

3. We also need to let the data repeater control know when any of the Text properties change. Add this code to the two text box Change events:

Private Sub txtPhone_Change() PropertyChanged "PublisherName" End Sub Private Sub txtPublisher_Change() PropertyChanged "PublisherName" End Sub Under the Tools menu, choose Procedure Attributes. Click on Advanced button. For both properties, under Data Binding check Property Is data bound and Show in data bindings collection at design time.

4. Resave the application.

Compile the ActiveX Control We’re now ready to compile and register the control so it becomes available for the data repeater (and any other Visual Basic project you may build). Choose the File menu option and click Make vbdbPublisher.ocx. Click OK. If you there are no errors in your code, the control will be compile and an OCX file saved in the directory you specify. Your control is now ready to use with the data repeater. Bind the ActiveX Control to the Data Repeater Control 1. Start a new Standard EXE application (a Visual Basic project). Add the data

repeater control and an ADO data control to your toolbox, then add them to your form. Set these properties:

Adodc1:

ConnectionString BIBLIO.MDB (point to working copy) CommandType 2-adCmdTable RecordSource Publishers

Page 257: VB6 DB Manual

Contents

© LAP II

cclvii

DataRepeater1: Caption Publisher Phone Numbers DataSource Adodc1 RepeatedControlName vbdbPublisher.ctlPublisher

To set the RepeatedControlName property, click the drop-down arrow that appears. You will be shown a list of all qualifying controls. Select the one we just created (vbdbPublisher.ctlPublisher). When you do this, the form is populated with the control. My form looks like this (you may have to do some resizing to get things to fit nicely):

2. We’re almost done – just one last step. We need to bind the properties of our

ActiveX control to fields in the database table connected to the data control (which is connected to the data repeater). Right-click the data repeater control and choose Properties. Select the RepeaterBindings tab. In the PropertyName combo box, choose PublisherName. In the DataField combo box, choose Company Name. Click Add to add the binding to the list box. Next, bind the PublisherPhone property to the Telephone data field. Click OK when done.

Page 258: VB6 DB Manual

Visual Basic and Databases

© LAP II

cclviii

3. Save the application. Run it and you should see:

You now have a scrollable list of Publisher phone numbers. Pretty cool, huh? This is a great tool for display multiple records without using the grid tools.

Page 259: VB6 DB Manual

Contents

© LAP II

cclix

Summary • There is wealth of material covered here. You now have a complete reference

to the Visual Basic toolbox and how those tools can be used for proper interface design. The Visual Basic interface is very important and we wanted to make sure you have many tools at your disposal. This will make your (and your user’s) task much easier.

• Even with all this work, our interface is not complete. We still need code that

allows us to edit, add, and delete records from a database. We need to know how to validate and save changes properly. We need to know how to ‘undo’ unwanted changes. We need to know how to properly exit an application. These topics, and more, are covered in the next chapter where we learn to design the total database management system.

Page 260: VB6 DB Manual

Visual Basic and Databases

© LAP II

cclx

Exercise 6

Publishers Table Input Form

In this chapter, we built the framework for an interface that allows us to maintain the Authors table in the books database (BIBLIO.MDB). This framework will be modified in the next chapter and implemented as part of a complete database management system. This database management system will also need interfaces to maintain the Publishers and Titles tables. The Titles table interface is a little tricky, in that it uses foreign keys to reference information in other tables. We will develop this interface in the next chapter. As an exercise here, we will begin the interface to maintain the Publishers table. We will follow the same steps used in this chapter to build the Authors table input form: o Build interface o Add message box(es) o Code application state o Perform entry validation o Perform input validation o Add error trapping and handling o Add on-line help system o Application testing Rather than starting from scratch, however, we will follow a ‘tried and true’ programming method – adapting an existing application to a new use. The Publishers table interface will essentially be the same as the Authors table interface. It will just have more (and different) input fields. Adapting an existing application saves us programmers a lot of time. You do have to make sure the modification implements the needs of the new application while at the same time eliminates vestiges of the old application. This exercise illustrates the modification steps followed and crosschecks required. An important step: Save your work often. You want to make sure your changes are always there. Recall these examples use the DAO data control. Modifications needed to use the ADO data control or ADO data environment are given in shaded boxes. Recall the naming convention we use for our files: no suffix (DAO), AD suffix (ADO data control), and DE (ADO data environment).

Page 261: VB6 DB Manual

Contents

© LAP II

cclxi

Build Interface 1. Open Example 6-8 (the last version of the Authors table input form).

Immediately resave the form with the name Exercise6.frm. Resave the project as Exercise6.vbp.

ADO Data Control Modifications Load Example6-8AD (the ADO data control version). Resave the form as Exercise6AD.frm. Resave the project as Exercise6AD.vbp.

ADO Data Environment Modifications Load Example6-8DE (the ADO data environment version). Resave the form as Exercise6DE.frm. Resave the project as Exercise6DE.vbp.

We now have a copy of the Authors table input form project to modify to a Publishers table input form. The Publishers table has ten (10) fields that must be input:

PubID Name Company Name Address City State Zip Telephone Fax Comments

We need a label and text box for each of these fields. We could use ten separate label and text box controls, each with separate names and properties. A better solution is to use control arrays to simplify bookkeeping chores and navigation among controls.

Page 262: VB6 DB Manual

Visual Basic and Databases

© LAP II

cclxii

2. Delete the label and text box control for the Author and Year Born fields (leaving only the Author ID label and text box). Resize the form so it is much taller (tall enough to hold ten labels and text boxes). Move the command buttons to the bottom of the resized form. Don’t worry where things are right now – they can always be resized and/or moved later. Copy and paste the label control until you have ten elements (Index 0 to 9) of a Label1 control array. Set the following Caption properties:

Label1 Index Caption

0 Publisher ID 1 Name 2 Company Name 3 Address 4 City 5 State 6 Zip 7 Telephone 8 Fax 9 Comments

Do any repositioning or resizing necessary.

3. At this point, my modified form looks like this:

Page 263: VB6 DB Manual

Contents

© LAP II

cclxiii

Change these properties:

frmAuthors (current name): Name frmPublishers Caption Publishers

datAuthors (current name):

Name datPublishers RecordSource SELECT * FROM Publishers ORDER BY Name

ADO Data Environment Modifications Add a new command object to conBooks connection object. Assign these properties: Command1: Name comPublishers ConnectionName conBooks CommandType 1-adCmdText CommandText SELECT * FROM Publishers ORDER BY

Name LockType 2-adLockOptimistic (allows editing)

4. In the cmdPrevious_Click and cmdNext_Click events, replace all

occurrences of datAuthors with datPublishers.

ADO Data Environment Modification Replace all occurrences of rscomAuthors with rscomPublishers.

Page 264: VB6 DB Manual

Visual Basic and Databases

© LAP II

cclxiv

5. Now, we’ll create the text box control array for each field. Set these properties for the one text box on the form:

txtAuthorID (current name):

Name txtInput DataSource datPublishers DataField PubID TabStop True

ADO Data Environment Modifications txtAuthorID: Name txtInput DataSource denBooks DataMember comPublishers DataField PubID TabStop True

Copy and paste this control until you have ten elements in the txtInput control array. Set the TabIndex and DataField properties for these controls:

txtInput Index TabIndex DataField

1 1 Name 2 2 Company Name 3 3 Address 4 4 City 5 5 State 6 6 Zip 7 7 Telephone 8 8 Fax 9 9 Comments

We now have ten text boxes bound to the fields of the Publishers database table, completing the interface appearance:

Page 265: VB6 DB Manual

Contents

© LAP II

cclxv

6. Save the application. Try running it – you’ll see this:

Click OK and you will be told that the variable txtAuthor (or perhaps some other variable) is not recognized. And, of course, it’s not. We just deleted it. This is what we meant by the need to remove vestiges (old code) from the application we are modifying. Trying to run the application will many times point out these “vestiges” to us. We’ll begin eliminating old code (as well as adding new code) in the next section.

Add Message Box(es) In its current state, all the message boxes within our code, except one, are generic in nature. These generic message boxes can be left as is. The one exception is the message box we added to inform the user if they typed an invalid date for the old Year Born field. This message box will be deleted in the next step.

Page 266: VB6 DB Manual

Visual Basic and Databases

© LAP II

cclxvi

Code Application State 1. In this step, we modify the code to reflect proper application state. We will

eliminate all old code, so when we are done the application will run without errors. The biggest changes are in the SetState procedure (this is the procedure that gave us the error message seen earlier). The modification locks and unlocks the text boxes, depending on state. The procedure is (new code is italicized):

Private Sub SetState(AppState As String) Dim I As Integer Select Case AppState Case "View" txtInput(0).BackColor = vbWhite For I = 1 To 9 txtInput(I).Locked = True Next I cmdPrevious.Enabled = True cmdNext.Enabled = True cmdAddNew.Enabled = True cmdSave.Enabled = False cmdCancel.Enabled = False cmdEdit.Enabled = True cmdDelete.Enabled = True cmdDone.Enabled = True txtInput(1).SetFocus Case "Add", "Edit" txtInput(0).BackColor = vbRed For I = 1 To 9 txtInput(I).Locked = False Next I cmdPrevious.Enabled = False cmdNext.Enabled = False cmdAddNew.Enabled = False cmdSave.Enabled = True cmdCancel.Enabled = True cmdEdit.Enabled = False cmdDelete.Enabled = False cmdDone.Enabled = False txtInput(1).SetFocus End Select End Sub

Page 267: VB6 DB Manual

Contents

© LAP II

cclxvii

2. Add this code to the txtInput_KeyPress event. This implements the code to programmatically move from text box to text box using the <Enter> key (as an alternate to using <Tab>):

Private Sub txtInput_KeyPress(Index As Integer, KeyAscii As Integer) If KeyAscii = vbKeyReturn Then If Index <> 9 Then txtInput(Index + 1).SetFocus Else txtInput(1).SetFocus End If End If End Sub

3. Save and run the application. You should now be able to move from record to

record and use the other command buttons to switch from state to state (don’t click Save or Help yet).

Perform Entry Validation We need to eliminate any old entry validations done and add required new ones. The only field that appears to need entry validation is Zip (it only uses numbers and hyphens, for 9 digit zips). We won’t add any validation, though. Why? Perhaps, in the future, the post office will develop a zip code with letters. We want to be ready for this possibility. And, other countries have a wide variety of zip formats. Since we are doing nothing but displaying this value, validation is not that important. If we were doing math with a value or using it in some other function, validation would take on greater importance. The old validation we need to eliminate is in the KeyPress event procedure for the txtYearBorn control. In fact, we can eliminate this entire procedure since the control no longer exits. Do this - note it is listed as a general procedure since there is no associated control. Also eliminate the txtAuthor_KeyPress event procedure (a general procedure).

Page 268: VB6 DB Manual

Visual Basic and Databases

© LAP II

cclxviii

Perform Input Validation Again, we need to eliminate any old input validations done and add required new ones. All of the inputs here are generic in nature and don’t need much validation. We will just insure a publisher Name field is entered. 1. Modify the ValidateData procedure to read (just eliminate the Year Born

validation and modify the Author Name validation a bit):

Private Sub ValidateData(AllOK As Boolean) Dim Message As String AllOK = True 'Check for name If Len(txtInput(1).Text) = 0 Then Message = "You must enter a Publisher Name." & vbCrLf & Message txtInput(1).SetFocus AllOK = False End If If Not (AllOK) Then MsgBox Message, vbOKOnly + vbInformation, "Validation Error" End If End Sub

You may be asking – isn’t the PubID field important enough to be validated? Well, yes, but being a primary key, it is treated differently. We will see how to handle this in Chapter 7.

2. Save the application and run it. Click Edit. Blank out the Publisher Name field and click Save. A message box should appear. Stop the application.

Add Error Trapping and Handling The error trapping and handling code in the old application still applies to the new application, hence no change is needed here. This is often the case in modifying existing applications. For other applications, you may need to modify existing error trapping schemes or add new ones.

Page 269: VB6 DB Manual

Contents

© LAP II

cclxix

Add On-Line Help System Use the Help Workshop to develop a help system named Publishers.hlp. 1. In your word processor, prepare a single topic file (Publishers.rtf). The topic I

used is:

#Publishers Input Form Available options for managing Publishers database table: Add New Record Click the Add New button to add a record to the Publishers database. Type in the requested fields. The Publisher Name is a required field. Click Save to save the new record; click Cancel to ignore the new record. Edit Record Click the Edit button to edit the displayed record. Make any needed changes. The Publisher Name is a required field. Click Save to save the changes; click Cancel to ignore the changes. Delete Record Click the Delete button to delete the displayed record. Exit Program Click the Done button to quit the application. #Topic1

Establish a topic ID (we used Topic1) footnote for the one topic.

2. In the Help Workshop, prepare a contents file (Publishers.cnt) and a project

file (Publishers.hpj). For each file, you might like to modify the corresponding Authors files and resave them with new names. Create the help file (Publishers.hlp).

Page 270: VB6 DB Manual

Visual Basic and Databases

© LAP II

cclxx

3. Go back to your application in Visual Basic. Click Project, then Properties. Set the Help File name. Change the code in the cmdHelp_Click procedure to read:

Private Sub cmdHelp_Click() Dim Rtn As Long Rtn = WinHelp(frmPublishers.hwnd, App.HelpFile, HELP_FINDER, CLng(0)) End Sub

4. Save the application. Run it. Make sure both the <F1> key and Help button

bring up the help system properly. Application Testing If you did all the above steps carefully, the application should be running properly. If not, make the changes required to get in running. As with the Authors form, we still need code to add the database management functions. This is addressed in the next chapter.