+ All Categories
Home > Documents > Visual Basic 6 Con ejemplos

Visual Basic 6 Con ejemplos

Date post: 31-Oct-2015
Category:
Upload: diego-herrera
View: 84 times
Download: 1 times
Share this document with a friend
Description:
Este es un manual con el cual podrás iniciarte en la programación de Visual Basic 6. Contiene la mayor cantidad de elementos necesarios para el nivel principiante y podrás ya realizar varios ejemplos prácticos con ejemplos.
Popular Tags:

of 270

Transcript
  • Visual Basic and Databases

    LAP II ISPGAYA

  • 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.

  • 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

  • Visual Basic and Databases

    LAP II

    iv

    3. Database Connection with the DAO Data Control Review and Preview ..................................................................................3-1 DAO or ADO Whats 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

  • 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 Whats 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

  • 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

  • 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

  • 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

  • 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

  • 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. Well take a brief look at what databases are, where they are used, and how Visual Basic is used with databases. And, well review the Visual Basic development environment and the steps followed to build an application in Visual Basic.

  • 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

  • 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 youve 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.

  • 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 librarys book database.

    When you go on-line and purchase some product, you are accessing the web merchants 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 stores 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 teams database (apologies to our foreign readers who dont 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).

  • 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 users)

    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, lets take a look at how Visual Basic fits into the database management system.

  • 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.

  • 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.

    Thats right - all the database tasks mentioned above can be done without writing one line of code! Thats 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 dont 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, lets review the steps in building a Visual Basic

    application and then build a simple application for practice.

  • 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)

  • 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.

    Well 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.

  • 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

  • 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 monitors screen:

  • 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.

  • 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 (well 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

  • 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.

  • 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)

  • 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

  • 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)

  • 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

  • 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]

  • 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

  • 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

  • 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(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

  • 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

  • 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.

  • 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.

  • 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.

  • 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

  • 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 products 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 manufacturers 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). Lets look at its relational structure to illustrate the many new concepts being introduced.

  • 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.

  • 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.

  • 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!

  • Contents

    LAP II

    xli

    Sample Database Structure Lets examine the books database a little closer. To help, well 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.

  • 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. Lets 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

  • 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 doesnt exist as a native table in the BIBLIO.MDB database it was formed using the native four tables.

  • 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. Its 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 (well 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.

  • 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.

  • 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.

  • Contents

    LAP II

    xlvii

    DAO or ADO Whats 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 whats 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 dont 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.

  • Visual Basic and Databases

    LAP II

    xlviii

    DAO Data Control The DAO data control is selected from the Visual Basic toolbox window. Its

    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.

  • 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 controls 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)

  • 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 propertys 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:

  • 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).

  • 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:

  • 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.

    Well 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, dont

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

    Label1:

    Caption Title

    Label2: Caption Year Published

  • Visual Basic and Databases

    LAP II

    liv

    Label3: Caption ISBN

    Label4:

    Caption Publisher ID

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

    Text2:

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

    Text3:

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

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

  • 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 didnt have to write one line of Visual Basic code! This indicates the power behind the data control and data bound controls.

    Theres one last thing. If you load this example from the code accompanying the course, you will need to reset the data controls 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.

  • 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.

  • 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.

  • 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.

  • 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 controls 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.

  • Visual Basic and Databases

    LAP II

    lx

    Quick Example 1 - Recordset Navigation 1. Load the project built in Example 3-1. Set the data controls 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

  • 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?

  • 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 dont 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 youre feeling overwhelmed by all the material presented herein, dont worry -

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

  • 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. Well

    develop a form where we can look through the Customers table in the Northwind Traders database.


Recommended