Visual Basic Database How-To Table of Contents: q Introduction q Chapter 1: - Accessing a Database with Bound Controls q Chapter 2: - Accessing a Database with Data Access Objects q Chapter 3: - Creating Queries with SQL q Chapter 4: - Designing and Implementing a Database q Chapter 5: - Microsoft Access Database q Chapter 6: - Connecting to an ODBC Server q Chapter 7: - SQL Server Databases and Remote Data Objects q Chapter 8: - Using ActiveX Data Objects q Chapter 9: - Microsoft Data Report q Chapter 10: - Security and Multiuser Access q Chapter 11: - The Windows Registry and State Information q Chapter 12: - ActiveX and Automation q Chapter 13: - Advanced Database Techniques q Appendix A: - SQL Reference q Appendix B: - Data Access Object Reference q Appendix C: - Remote Data Object Reference q Appendix D: - ActiveX Data Objects Reference q Appendix E: - A Short Introduction to Visual Basic Objects © Copyright, Macmillan Computer Publishing All rights reserved Visual Basic Database How-To Introduction Visual Basic Database How-To q About This Book q What You Need to Use This Book Introduction About This Book Since version 3, Visual Basic has been the tool of choice for database programmers everywhere First came DAO with version 3, RDO with version 4, and then the ability to build robust ActiveX components in version With each successive version, Microsoft adds more functionality to make database programming easier for you Visual Basic's powerful database feature set has continued to grow with version New tools and technologies like ADO, OLE-DB, and the Microsoft Data Reporter vie for your attention What does it all mean, what can it for you, and most importantly, how you quickly get up to speed? That's why this book was created Visual Basic Database How-To gives an in-depth view of each major method of data access, with real-life examples with which to work Like all books in the successful How-To series, Visual Basic Database How-To emphasizes a step-by-step problem-solving approach to Visual Basic programming Each How-To follows a consistent format that guides you through the issues and techniques involved in solving a specific problem Each section contains the steps to solve a problem, as well as a discussion of how and why the solution works In most cases, you can simply copy the provided code or objects into your application and be up and running immediately All the code described in the book is available on the accompanying CD-ROM The book's concepts and examples are useful to Visual Basic programmers of all skill levels Each How-To is graded by complexity level, with information on additional uses and enhancements to fit your needs exactly Additionally, each chapter contains an introduction that summarizes each How-To and covers the chapter's techniques and topics so that you can zero in on just the solution you need without having to go through hundreds of pages to find it http://www.pbs.mcp.com/ebooks/1571691529/fm/fm.htm (1 of 4) [9/22/1999 1:56:43 AM] Visual Basic Database How-To Introduction What You Need to Use This Book You need Visual Basic 6, Professional or Enterprise Edition This book was written using Visual Basic Enterprise Edition, but most sections will work with the Professional Edition Many of the sections will also work with Visual Basic 5, but specific references to menu selections and windows may have changed between versions You may have to improvise the How-To's to make the samples work with Visual Basic Most chapters avoid using controls or tools not included with Visual Basic 6, Professional or Enterprise Edition However, much of Visual Basic's strength is its extensibility using third-party tools and controls You are encouraged to explore third-party offerings; they can often cut significant time from the development cycle About the Authors Eric Winemiller is a principal software developer for Visteon Corporation in Maitland, Florida, where he builds BackOffice- and Visual Basic-based medical applications The project he helped develop for Orlando Health Care Group and Visteon Corporation placed 10th in Info World's 1995 Top 100 client server sites Eric has previously published in Visual Basic Developer, SQL Server Professional, and the Visual Basic SuperBible He has a bachelor's degree in computer science from the University of Central Florida His family considers the Commodore 64 they gave him for his 13th birthday the best 200 bucks they ever spent In his spare time he can be found trying to be a digital artist, puttering around his wood shop, or renovating his old house He can be reached at winemill@visteon.com Jason T Roff currently works for Isogon Corporation, a company that provides asset management solutions to Fortune 500 companies Here he develops C/C++ client/server applications that are designed to run on heterogeneous networks Jason holds a bachelor's degree from the University at Albany, New York, in computer science with applied mathematics Jason can be reached at jroff@earthlink.net Bill Heyman specializes in custom software development for Windows 98 and Windows NT in Visual Basic, C++, and Java As founder and president of Heyman Software, Inc., Bill uses his skills and experience to engineer innovative software for his clients He can be reached at heyman@heymansoftware.com and http://www heymansoftware.com/~heyman/ Ryan Groom has been a computer addict since getting a Commodore 64 for Christmas back in 1985 After graduation he started work for a local school board where he cut his teeth on various computer topics from administering OS/2 and Novell servers to creating attendance management software In 1996, he co-founded Gulliver Software in Saint John, New Brunswick, Canada Gulliver Software develops Internet-based software, including its retail package Gulliver's Guardian, an Internet filtering suite for families Currently Ryan (and Gulliver Software) is working with National Electronic Technologies on a releasing a public Internet access terminal called VideoNet Ryan can be reached at ryan@gulliver.nb.ca, or you can visit him at http://www.gulliver.nb.ca or http://www.natel.ca http://www.pbs.mcp.com/ebooks/1571691529/fm/fm.htm (2 of 4) [9/22/1999 1:56:43 AM] Visual Basic Database How-To Introduction Dedication To my parents, who got me started down the path Eric Winemiller To my sister Tammi, who has put up with all my beatings, has kept all my secrets, and can drink me under the table I love you Jason Roff To my parents, for giving me an Apple II+ and the start to a wonderful career Bill Heyman For Kristy Our new life has just begun Ryan Groom Acknowledgements I want to thank my wife Judy for again putting up with the grumpy foul beast who possesses me when I don't get enough sleep I would also like to thank the Clinical and Clinical beta teams at Visteon who had to put up with that same beast Eric Winemiller I would like to thank everybody at Macmillan who was gracious enough to give me another opportunity to what I love, write I would especially like to thank Brian Gill, Ron Gallagher, and Chris Nelson I would also like to thank my other half, Kimberly, for putting up with many nights of not seeing me so that I could work to finish projects such as this book I love you so very much, and I cannot wait to spend the rest of my life with you Jason Roff I want to extend my thanks to the kind folks at Macmillan Computer Publishing for assisting me in contributing to this book In addition, I would like to acknowledge the continuing love and support that my wife, Jodi, and toddler daughter, Cassie, give to me Certainly I would not be where I am today without them Bill Heyman To the staff at Macmillan Computer Publishing for providing the opportunity and patience for allowing me write about one of my favorite topics It is very fulfilling to not only to be involved in such an exciting industry but also to have an opportunity to create documentation that may let others understand a topic I so enjoy The gang at Gulliver Software and National Electronics for providing a fun and innovative atmosphere in which to work Rory, a brother in arms, "You know what I mean, man!" Mom, Dad, Michael, and Peter, for your eternal support for every step I take Steven and Dawn for providing a http://www.pbs.mcp.com/ebooks/1571691529/fm/fm.htm (3 of 4) [9/22/1999 1:56:43 AM] Visual Basic Database How-To Introduction great get away from the woes of computerdom Kristy, only with your support, patience, and understanding can any project be completed Ryan Groom Tell Us What You Think! As the reader of this book, you are our most important critic and commentator We value your opinion and want to know what we're doing right, what we could better, what areas you'd like to see us publish in, and any other words of wisdom you're willing to pass our way As the Executive Editor for the Programming team at Macmillan Computer Publishing, I welcome your comments You can fax, email, or write me directly to let me know what you did or didn't like about this book as well as what we can to make our books stronger Please note that I cannot help you with technical problems related to the topic of this book, and that due to the high volume of mail I receive, I might not be able to reply to every message When you write, please be sure to include this book's title and author as well as your name and phone or fax number I will carefully review your comments and share them with the authors and editors who worked on the book Fax: 317-817-7070 Email: prog@mcp.com Mail: Executive Editor Programming Macmillan Computer Publishing 201 West 103rd Street Indianapolis, IN 46290 USA © Copyright, Macmillan Computer Publishing All rights reserved http://www.pbs.mcp.com/ebooks/1571691529/fm/fm.htm (4 of 4) [9/22/1999 1:56:43 AM] Visual Basic Database How-To Ch Accessing a Database with Bound Controls Visual Basic Database How-To -1Accessing a Database with Bound Controls q How I r 1.1 Browse a recordset using bound controls? r 1.2 Validate data entered into bound controls? r 1.3 Allow users to undo changes they've made in bound controls? r 1.4 Add and delete records using bound controls? r 1.5 Create and use bound lists? r 1.6 Display many detail records for a single master record? r 1.7 Change data in data-bound grid cells from code? r 1.8 Gracefully handle database errors? The Microsoft Jet database engine, supplied with Visual Basic, gives you the ability to access many types of databases Microsoft Access databases; other PC-based databases such as dBASE, FoxPro, Paradox, and Btrieve; and any relational database that supports the open database connectivity (ODBC) standard Visual Basic provides two basic techniques for working with the Jet database engine: the data control and the data access objects (DAO) The data control requires less code, but data access objects are much more flexible This chapter shows you how to use the data control to perform common database operations Chapter 2, "Accessing a Database with Data Access Objects," describes the use of data access objects VISUAL BASIC TERMINOLOGY PRIMER If you're new to database programming, many Visual Basic terms might be new to you Visual Basic works with all databases through a recordset consisting of all the records in a table or all the records satisfying a particular Structured Query Language (SQL) SELECT statement A SELECT statement asks the database to retrieve specified database fields from one or more database tables in which record fields meet certain criteria SQL itself is discussed in Chapter 3, "Creating Queries with SQL." The programmer's interaction with the user is through visual controls placed on the form for data http://www.pbs.mcp.com/ebooks/1571691529/ch01/ch01.htm (1 of 37) [9/22/1999 1:56:52 AM] Visual Basic Database How-To Ch Accessing a Database with Bound Controls entry, command buttons, menus, labels, list boxes, and so on The most common controls are text boxes for entering data, command buttons for getting the program to useful work, menus, and labels to describe the other controls List boxes and combo boxes allow the program to provide the user with multiple selections for text entry Most visual controls, including text, list, and combo boxes, can be bound to a data source for automatic display of data or have a special data-bound version Binding is the process of connecting the data in a visual control to a field in a recordset The most common binding method is the data control The data control has a visual interface to support data movement through the records and a recordset object to manage the interface to the database engine The data control component also supports several methods and properties for programmatic or design-time control A component is simply a "piece part" used to build a Visual Basic application A method is equivalent to a function call to the component to get the component to useful work A property is a data element of the component that helps control its behavior For example, the data control has a DatabaseName property to tell it where the database can be found and a Move method to move the visual control around on the form In addition, the data control exposes all the methods and properties of its contained recordset object All examples in this chapter use existing Microsoft Access database files delivered with Visual Basic (later chapters demonstrate how to create a database with Visual Basic) The techniques, however, apply to all the databases that Visual Basic can access through the Jet engine In addition, the Enterprise Edition remote data control uses very similar techniques for direct use with ODBC databases The remote data control bypasses the Jet engine and usually delivers faster performance than access through the Jet engine 1.1 Browse a Recordset Using Bound Controls One of the most fundamental operations in database work is the user's ability to browse through records in an existing database and modify data In this How-To, you'll use the data control, bind its fields to some text boxes, and write one line of executable code to browse a database 1.2 Validate Data Entered into Bound Controls People make data entry errors, and an industrial-strength application anticipates and traps those errors before the data entry errors corrupt the integrity of the database This How-To shows how to trap and respond to entry errors when you're using the data control and bound visual controls 1.3 Allow People to Undo Changes They've Made in Bound Controls Sometimes people catch their own mistakes In this How-To, you'll learn how to enable them to undo those mistakes when the application uses the data control 1.4 Add and Delete Records Using Bound Controls A database is fairly useless without some means of adding and deleting records In this How-To, you'll see how to add and delete records with bound controls 1.5 Create and Use Bound Lists One way to reduce data entry errors and make people's lives a bit easier is to provide people with lists from which they can choose appropriate values for database fields Visual Basic provides the DBCombo and DBList http://www.pbs.mcp.com/ebooks/1571691529/ch01/ch01.htm (2 of 37) [9/22/1999 1:56:52 AM] Visual Basic Database How-To Ch Accessing a Database with Bound Controls controls that make this easy to In this How-To, you'll use the DBCombo control to display suggested field values 1.6 Display Many Detail Records for a Single Master Record Frequently, you need to work with related records at the same time in a master-detail relationship You might want to show an invoice header and all its detail lines or show all the orders for a particular product This How-To shows how the DBGrid control can place multiple detail records on a form for each master record 1.7 Change Data in Data-Bound Grid Cells from Code The master-detail grid looks great, but some applications require the capability to expand and edit grid data from the main form This How-To walks through a form that edits DBGrid data from the form's code 1.8 Gracefully Handle Database Errors Whenever you're working with disk files, unanticipated errors can occur Your Visual Basic database program should handle errors gracefully This How-To shows how FINDING THE SAMPLES All the How-To's in this book are on the accompanying CD-ROM After you install the source code, you will find a directory for each chapter; and within each chapter directory there is a directory for each How-To The steps of each How-To start with an opportunity to preview the completed How-To from your installation directory If you decide to work through a How-To in its entirety, we assume that you are working in a separate work area on your computer 1.1 How I BROWSE A RECORDSET USING BOUND CONTROLS? Problem I need to see the records in a database, but I don't want to write a lot of code How can I this with Visual Basic? Technique The Visual Basic data control object, in conjunction with data-bound controls, allows you to browse records in a supported database without writing a single line of code To use the data control, place it on your form and set two properties: DatabaseName, which specifies the database to which it will be linked, and RecordSource, which designates the source of data within the database Add a text box to your form for every database field you want to access from the RecordSource, and bind each text box to the data control object and RecordSource field COMPATIBLE DATABASES Databases that are compliant with the Visual Basic data control and with Visual Basic data access objects, discussed in Chapter include Microsoft Access, dBASE, FoxPro, Paradox, Btrieve, and http://www.pbs.mcp.com/ebooks/1571691529/ch01/ch01.htm (3 of 37) [9/22/1999 1:56:52 AM] Visual Basic Database How-To Ch Accessing a Database with Bound Controls any other database products that support the ODBC standard Most relational database products for desktop systems and multiuser systems support ODBC The examples throughout this book use Microsoft Access databases, except for those in Chapters 6, "Connecting to an ODBC Server," and 7, "SQL Server Databases and Remote Data Objects," which relate specifically to other database products Virtually all the examples in the book (except for those in Chapters and 7) can be applied to any of the database products When you work with Microsoft Access databases, DatabaseName is the name of a Microsoft Access database file When you work with other database products, what constitutes "the database" depends on the type of database for dBASE, Paradox, and FoxPro databases, for example, DatabaseName is the name of the directory in which data files are stored RecordSource can also be a table or a SQL SELECT statement Microsoft Access also allows you to specify the name of a query stored within the database as the RecordSource The data control not only provides the link between your form and the database, but it also provides tools for navigating through the database Figure 1.1 shows a data control The Next Record and Previous Record buttons move you through the database one record at a time The First Record and Last Record buttons move you quickly to the beginning or end of the database Figure 1.1 The data control Steps To preview this How-To, open the project BrowseBound.VBP in the Chapter01\HowTo01 directory Change the DatabaseName property of the data control datEmployees to point to the copy of NWind.MDB installed on your system (probably in the directory where VB6.EXE is installed) Then run the project The form shown in Figure 1.2 appears Use the buttons on the data control to view records in the Titles table of NWind.MDB Figure 1.2 The Bound Browser form Create a new project in your work area called BrowseBound.VBP Use Form1 to create the objects and properties listed in Table 1.1, and save the form as BrowseBound.FRM Substitute the path to your copy of NWIND.MDB for the DatabaseName property of datEmployees Table 1.1 Objects and properties for the Bound Browser form OBJECT Property Setting Form Form1 "Bound Browser" datEmployees Data Name Caption Name Caption "Employees" DatabaseName "D:\Program Files\Microsoft Visual Studio\VB6\NWIND.MDB" RecordSource "Employees" TextBox Name DataField DataSource txtEmpLastName "LastName" "datEmployees" http://www.pbs.mcp.com/ebooks/1571691529/ch01/ch01.htm (4 of 37) [9/22/1999 1:56:53 AM] Visual Basic Database How-To Appendix D ACTIVEX DATA OBJECTS REFERENCE Table D.4 Connection Object Methods METHOD BeginTrans Cancel Close Execute Open OpenSchema Description Begins a transaction Cancels an asynchronous operation Closes an object Executes a SQL statement or query Open the connection Returns a Recordset object filled with database information RollbackTrans Rolls back a transaction Table D.5 Connection Object Properties PROPERTY Attributes CommandTimeout ConnectionString ConnectionTimeout CursorLocation DefaultDatabase Errors IsolationLevel Mode Properties Provider State Version Description Indicates characteristics of the object Returns or sets the timeout for the Execute method Returns or sets the connection string Returns or sets the timeout to establish a connection Returns or sets where the cursor is created Returns or sets the default database Returns the collection of Error objects raised by data providers Returns or set the level of isolation for transactions Returns the available permissions for modifying data Returns the dynamic properties for the object Returns the name of the data provider Returns the current state of the object Returns the ADO version number Errors Collection, Error Object The Errors collection and Error object manage the data provider generated errors for a Connection object Tables D.6 and D.7 list the methods and properties for the Errors collection Table D.8 lists the properties for the Error object Table D.6 Errors Collection Methods METHOD Description http://www.pbs.mcp.com/ebooks/1571691529/apd/apd.htm (3 of 9) [9/22/1999 2:24:52 AM] Visual Basic Database How-To Appendix D ACTIVEX DATA OBJECTS REFERENCE Clear Refresh Clears the collection Refreshes the items in the collection Table D.7 Errors Collection Properties PROPERTY Description Count Returns the number of items in the collection Item Returns the specified object from the collection Table D.8 Error Object Properties PROPERTY Description Description Returns the description of the error HelpContext HelpFile NativeError Number Source SQLState Returns a Help Context Id if a HelpFile is available Returns the name of a help file where help on the error is available Returns the error number reported by the underlying API or interface Returns the error number Returns the name of the source of the error Returns the five-character ANSI standard error Fields Collection, Field Object The Fields collection and Field object are the columns or fields returned in a Recordset object Table D.9 summarizes the methods of the Fields collection Table D.10 describes the properties of the Fields collection Tables D.11 and D.12 lists the methods and properties of the Field object Table D.9 Fields Collection Methods METHOD Append Delete Refresh Description Appends an object to the collection Deletes an object from the collection Refreshes the items in the collection Table D.10 Fields Collection Properties PROPERTY Description Count Returns the number of items in the collection Item Returns the specified object from the collection http://www.pbs.mcp.com/ebooks/1571691529/apd/apd.htm (4 of 9) [9/22/1999 2:24:52 AM] Visual Basic Database How-To Appendix D ACTIVEX DATA OBJECTS REFERENCE Table D.11 Field Object Methods METHOD Description AppendChunk Appends data to the object's value GetChunk Returns a portion of data from the object's value Table D.12 Field Object Properties PROPERTY ActualSize Attributes DataFormat DefinedSize Name NumericScale Description Returns the size of the field Indicates characteristics of the object Returns or sets the stdDataFormat object The defined size of the field The name of the object Returns or sets the number of decimal places to which numeric values will be resolved OriginalValue Returns the values of the field when the Recordset was first opened Precision Returns or sets the maximum number of digits used to represent values Properties Returns the dynamic properties for the object Type Returns the datatype UnderlyingValue Returns the object's current value in the database Value Returns the object's current value in the Recordset Parameters Collection, Parameter Object The Parameters collection and Parameter object are used with the Command object to execute stored procedures Tables D.13 and D.14 list the methods and properties for the Parameters collection Table D.15 lists the method for the Parameter object, and Table D.16 lists the properties of the Parameter object Table D.13 Parameters Collection Methods METHOD Append Delete Refresh Description Appends an object to the collection Deletes an object from the collection Refreshes the items in the collection Table D.14 Parameters Collection Properties http://www.pbs.mcp.com/ebooks/1571691529/apd/apd.htm (5 of 9) [9/22/1999 2:24:52 AM] Visual Basic Database How-To Appendix D ACTIVEX DATA OBJECTS REFERENCE PROPERTY Description Count Returns the number of items in the collection Item Returns the specified object from the collection Table D.15 Parameter Object method METHOD Description AppendChunk Appends data to the object's value Table D.16 Parameter Object Properties PROPERTY Description Attributes Indicates characteristics of the object Direction Name NumericScale Precision Properties Size Type Value Returns or sets the direction of the parameter The name of the object Returns or sets the number of decimal places to which numeric values will be resolved Returns or sets the maximum digits used to represent values Returns the dynamic properties for the object Returns the maximum size of the object Returns the datatype Returns the object's value Properties Collection, Property Object The Properties collection and the Property object manage dynamic characteristics for an ADO object Tables D.17 and D.18 list the methods and properties of the Properties collection Table D.19 lists the properties of the Property object Table D.17 Properties Collection Method METHOD Description Refresh Refreshes the items in the collection Table D.18 Properties Collection Properties PROPERTY DESCRIPTION Count Returns the number of items in the collection Item Returns the specified object from the collection http://www.pbs.mcp.com/ebooks/1571691529/apd/apd.htm (6 of 9) [9/22/1999 2:24:52 AM] Visual Basic Database How-To Appendix D ACTIVEX DATA OBJECTS REFERENCE Table D.19 Property Object Properties PROPERTY Attributes Name Type Value Description Indicates characteristics of the object The name of the object Returns the datatype Returns the object's value Recordset Object The Recordset object handles the rows returned from an opened table or executed query Tables D.20, D.21, and D.22 describe the events, methods, and properties of the Recordset object Table D.20 Recordset Object Events EVENT EndOfRecordset Description FetchComplete Fired when the entire Recordset is fetched Fired to indicate the progress of the data fetch Fired after a field is changed Fired when the end of the Recordset is reached FetchProgress FieldChangeComplete MoveComplete Fired after the Recordset moves to another record Fired after a record is changed RecordChangeComplete RecordsetChangeComplete Fired after the Recordset is changed WillChangeField Fired before a field's value is changed WillChangeRecord Fired before a record is changed WillChangeRecordset Fired before the Recordset is changed WillMove Fired before the Recordset moves to another record Table D.21 Recordset Object Methods METHOD AddNew Cancel CancelBatch Description Adds a new record to the object Cancels an asynchronously executing command CancelUpdate Cancels changes before an Update has been called Clone Returns a duplicate Recordset Cancels changes before BatchUpdate has been called http://www.pbs.mcp.com/ebooks/1571691529/apd/apd.htm (7 of 9) [9/22/1999 2:24:52 AM] Visual Basic Database How-To Appendix D ACTIVEX DATA OBJECTS REFERENCE Close Closes the object CompareBookmarks Compares two bookmarks Delete Deletes from the Recordset Find Finds a record in the Recordset GetRows GetString Move MoveFirst Retrieves records into an array Retrieves records into a string Moves the position of the current record MoveLast Moves to the last record of the Recordset MoveNext Moves to the next record of the Recordset MovePrevious Moves to the previous record of the Recordset NextRecordset Clears current Recordset and moves to the next Recordset Opens the object Open Requery Moves to the first record of the Recordset Refreshes the Recordset by re-executing the underlying query Resync Refreshes the Recordset to the current database values Save Saves the Recordset to a file Returns whether the object supports a particular function Saves the changes to the current row to the database Saves the changes of the current batch to the database Supports Update UpdateBatch Table D.22 Recordset Object Properties PROPERTY AbsolutePage AbsolutePosition ActiveCommand Description Returns or sets the page of the current record Returns or sets the current record position by ordinal Returns the command object that created the Recordset ActiveConnection Returns the active connection used by the Recordset BOF Returns whether the current record position is before the beginning of the Recordset Bookmark Returns or sets a bookmark for the current record CacheSize Returns or sets the number records that will be cached in local memory CursorLocation Returns or sets where the cursor will be created CursorType Returns or sets the type of cursor DataMember Returns or sets the data member to retrieve from the object referenced by the datasource property DataSource Returns or sets the object containing data the Recordset represents http://www.pbs.mcp.com/ebooks/1571691529/apd/apd.htm (8 of 9) [9/22/1999 2:24:52 AM] Visual Basic Database How-To Appendix D ACTIVEX DATA OBJECTS REFERENCE EditMode EOF Returns the editing status of the current record Fields Returns the collection of Field object's in the Recordset Returns or sets the filter for data Returns or sets the locking strategy Filter LockType MarshalOptions MaxRecords PageCount PageSize Properties RecordCount Sort Source State Status StayInSync Returns if the current record position is past the end of the Recordset Returns or sets how the Recordset should be marshaled using DCOM Returns or sets the maximum number of records to return Returns the number of pages the Recordset contains Returns or sets the size of the pages Returns the dynamic properties for the object Returns the number of records Returns or sets the sort criteria Returns or sets the source of the data Returns the current state of the object Returns the status with regards to batch updates Returns or sets whether the parent row should change when underlying child rows change in a hierarchical Recordset © Copyright, Macmillan Computer Publishing All rights reserved http://www.pbs.mcp.com/ebooks/1571691529/apd/apd.htm (9 of 9) [9/22/1999 2:24:52 AM] Visual Basic Database How-To Appendix E A Short Introduction to Visual Basic Objects Visual Basic Database How-To -EA Short Introduction to Visual Basic Objects q Object Overview q Your Own Object q Collections of Objects r Adding an Item to a Collection Object r Removing an Item from a Collection Object r Accessing Items in a Collection Object The introduction of Visual Basic made object-oriented programming much easier This appendix defines and discusses objects as well as illustrates how to use them Object Overview The biggest selling point of object-oriented programming is encapsulation Encapsulation means that both the data and the means of transforming or altering that data is wrapped up into one easy-to-use shell called an object In its simplest form, an object is a group of data describing a particular item that cannot be described by a single number or string For instance, imagine that you want to make yourself the object in which to store your application With a single variable, you can give yourself a name Most likely you need much more information than this to describe yourself You might want to indicate your age and possibly your address It is possible to incorporate all this information into one structure that represents you Take, for example, the following type declaration: Private Type Person Name As String http://www.pbs.mcp.com/ebooks/1571691529/ape/ape.htm (1 of 7) [9/22/1999 2:25:40 AM] Visual Basic Database How-To Appendix E A Short Introduction to Visual Basic Objects Age As Integer Address As String City As String State As String ZipCode As String End Type This declaration creates a new data type called Person that can hold a person's name, age, address, city, state, and zip code To create a new person, you would use something similar to the following declaration: Private Steven As Person This data structure was acceptable to Visual Basic programmers until version 6, when developers suddenly demanded more (and we have the right!) Now, in Visual Basic 6, you can include much more in a data structure than just the data Using encapsulation, you can add methods and events The data, as we know it, becomes properties Properties are user-interface variables or variable objects With these interfaces, you can cleanly access the data for what is now called a class The concept of classes was not developed for Visual Basic; it was developed a long time ago for much older languages (If I quote a language that invented classes or object-oriented programming, I know I will receive hate mail telling me of an earlier programming language, so I'll be vague in my history.) What's important is that you have the ability to use classes now in Visual Basic A class is similar to a type declaration in that it is a framework or a shell used to hold and manipulate data; however, no data or manipulation occurs in the class itself To work with this structure, you must create an instance of the class by declaring a variable an object variable: Private m_oNewPerson As New Person Here, Person is no longer the name of a data structure but rather the name of a class that would hold properties called Name, Age, Address, and so on You would also have methods within this class to manipulate this information For instance, you might have a method that is part of the Person class that would load a person's information from a file In this case, you might have a Load method, as in this example: m_oNewPerson.Load "Steven" This example accepts a string as an argument to determine the name of the person to load There have always been objects in Visual Basic, even if you haven't realized it Take, for instance, the TextBox control This is an object an instance of the text box class You can use object-oriented programming to access the properties of a TextBox control as shown in this procedure: Private Sub DoSomethingSenseless() Text1.Enabled = True Text1.Text = "Hello Mommy!" Text1.SelStart = Text1.SelLength = Len(Text1.Text) End Sub This example simply sets various properties of the TextBox control to what you have specified You also http://www.pbs.mcp.com/ebooks/1571691529/ape/ape.htm (2 of 7) [9/22/1999 2:25:40 AM] Visual Basic Database How-To Appendix E A Short Introduction to Visual Basic Objects read one of the properties from the TextBox control (Text1.Text), as shown in the last line You can call methods of this control in a fashion similar to this: Text1.SetFocus In this example, you simply called the SetFocus method that puts the focus of the window to the TextBox control The DoSomethingSenseless routine shown previously takes advantage of a great interface to the TextBox control However, there is an even more object-oriented approach you can choose to take, as shown in this newly revised DoSomethingSenseless routine: Private Sub DoSomethingSenseless() With Text1 Enabled = True Text = "Hello Mommy!" SelStart = SelLength = Len(.Text) SetFocus End With End Sub This routine uses a statement called With With uses the Text1 control to access its public members Many objects have default properties The TextBox control's default property is the Text property The following example shows how you can access the default property: Private Sub DoMoreThings() ` declare a new object and call it oNewObject Dim oNewObject As Object ` all objects can be set to the `root' type of Object Set oNewObject = Text1 ` the following are equivalent oNewObject.Text = "Hello Dad!" oNewObject = "Hello Dad!" Text1.Text = "Hello Dad!" Text1 = "Hello Dad!" End Sub Notice the declaration of a new object variable in the beginning of this routine All objects can be assigned to the Object data type This means that all objects implement the object class After you have the new object, you can set it to the Text1 control (actually, just give it a reference to the control) This step allows you to access your Text1 control using the oNewObject object variable Also notice that the Text property does not have to be entered to assign the property its value because it is the object's default value Your Own Object You can create your own object definition, or class, using Visual Basic To so, first create a new project Along with Form1, which should already be part of your new project, add a class module Name the class Person, and add the following code to the declarations section of the class module: http://www.pbs.mcp.com/ebooks/1571691529/ape/ape.htm (3 of 7) [9/22/1999 2:25:40 AM] Visual Basic Database How-To Appendix E A Short Introduction to Visual Basic Objects Option Explicit Private m_sFirstName As String Private m_sLastName As String These two member variables of the Person class are private variables they cannot be accessed by anybody outside of your class Now add your public properties, which serve as your user interface to retrieve information from the user: Public Property Let FirstName(ByVal sNewValue As String) m_sFirstName = sNewValue End Property Public Property Let LastName(ByVal sNewValue As String) m_sLastName = sNewValue End Property Please note that there are no Property Get routines for the FirstName and LastName properties This means that the properties are write-only and cannot be read Now create a property that allows the user to retrieve the entire name of the Person class as shown here: Public Property Get FullName() As String FullName = m_sFirstName & " " & m_sLastName End Property This is a Property Get routine, and there is no Property Let routine, so this property is read-only You can now use your new class in a routine to create a new Person object: Private Sub CreatePerson() Dim oNewPerson As New Person With oNewPerson ` retrieve information from the user FirstName = InputBox$("Enter first name:") LastName = InputBox$("Enter last name:") ` display the full name for the user MSGBOX "PERSON'S FULL NAME: " & FULLNAME End With End Sub This routine declares a new instance of the Person class that you wrote earlier The user is then asked for the first and last name of the new person, and both strings are stored in the corresponding property Finally, the FullName property is called to show the user the full name of the new person Collections of Objects Collections are used to group related data objects into a single set In DAO, collections are everywhere from the Workspaces collection to the Fields and Indexes collections A collection is a good place to keep a list of objects For instance, take the Person class shown previously http://www.pbs.mcp.com/ebooks/1571691529/ape/ape.htm (4 of 7) [9/22/1999 2:25:40 AM] Visual Basic Database How-To Appendix E A Short Introduction to Visual Basic Objects Suppose you want to add many people to a group or list In this case, it would be good to use the Collection class to keep track of the people Take the following event, for example: Public Persons As New Collection Private Sub cmdAddPerson_Click() ` initiate a new person object Dim oNewPerson As New Person With oNewPerson ` get new name from the user FirstName = InputBox$("Enter first name:") LastName = InputBox$("Enter last name:") ` add the person to the persons collection Persons.Add FullName End With End Sub This event fires when a person presses a command button First, a new Person object is initiated from the Person class Next, the person's first and last names are filled Finally, the person is added to the collection using the Add method of the Persons collection The Collection class stores all items as Variant data types Therefore, you can add any data type to a collection object, with the exception of user-defined types This also means that you can add different types to the same collection because the Collection class cannot tell the difference anyway Table E.1 shows the property and three methods of the Collection class Table E.1 The Collection class METHOD OR PROPERTY Description Returns the number of items belonging to the current collection object Count property Add method Adds a new item to the current collection object Item method Returns an item, by an index or a key, from the current collection object Remove method Removes an item from the current collection, by an index or a key As you can see, the Collection class is pretty straightforward Although arrays are more efficient memory managers than collection objects, they cannot compete with other advantages For one, you never need to use ReDim with a collection object it takes care of its size for you Also, the Collection class can access its items very quickly using the Item method, whereas an array does not have this built-in functionality An item of a collection is retrieved, removed, or added to a collection object, using a key and an index A key is a string used during the Add method call, whereas an index is usually determined after each object is added to a collection An index is a long value that can be determined by using the before and after parameters; however, the index can change after another object is added to the collection You can use the index to iterate through a collection to access each item, as shown in this example: Dim nCount As Integer With Persons http://www.pbs.mcp.com/ebooks/1571691529/ape/ape.htm (5 of 7) [9/22/1999 2:25:40 AM] Visual Basic Database How-To Appendix E A Short Introduction to Visual Basic Objects For nCount = To Count Debug.Print Item(nCount).FullName Next nCount End With This code uses the Count property of the Persons collection to determine an upper bound for the For Next loop For each item in the collection object Persons, the FullName property is printed to the Immediate Window An easier and more efficient way to iterate through a collection is to use the For Each Next statement instead of the For Next, as shown in this code: Dim oPerson As Person For Each oPerson In Persons Debug.Print oPerson.FullName Next nCount This code declares a new object variable called oPerson as a Person object Using this variable, the For Each oPerson In Persons line of code sets oPerson to each Persons.Item(index) object in the collection Now you can use the oPerson object to access the collection object Adding an Item to a Collection Object To add items to a collection, you would use the Add method with the following syntax: Sub Add (item As Variant [, key As Variant] [, before As Variant] [, after As Variant]) The first parameter to the routine is the actual object you are to add to the collection, and the second is a key that would be used to quickly search for the given object The following statements demonstrate the use of keys in a collection: Persons.Add oNewPerson, oNewPerson.FullName Persons.Add oNewPerson, "Jason" The other two parameters for the Add method are the before and after parameters By using one of these two parameters, you can specify the ordinal position of your item in the collection object as shown in these examples: Persons.Add oNewPerson, "Jason", ` adds as first item Persons.Add oNewPerson, "John", before:=3 ` adds as second item Persons.Add oNewPerson, "Kimberly", after:=6 ` adds as seventh item As you can see, the Add method supports named arguments Removing an Item from a Collection Object To delete an item from a collection, you must know the index or the key of the item intended for deletion The syntax for the Remove method is as follows: Sub Remove (index As Variant) http://www.pbs.mcp.com/ebooks/1571691529/ape/ape.htm (6 of 7) [9/22/1999 2:25:40 AM] Visual Basic Database How-To Appendix E A Short Introduction to Visual Basic Objects The index argument in the Remove method can be either the item's key or the item's index number Following are a couple examples of the Remove method: Persons.Remove Persons.Remove "Jason" Accessing Items in a Collection Object To access items in a collection, you can use the Item method The syntax for the Item method is as follows: Function Item (index As Variant) As Variant You must use the Set statement when the Item being returned is an object variable The index argument is either the key or the index of the item in the collection object, as shown in these examples: SET Set Set Set ONEWPERSON oNewPerson oNewPerson oNewPerson = = = = PERSONS.ITEM(6) Persons.Item("Jason") Persons(6) Persons("Jason") Notice the last two statements The Item method is omitted because it is the default method for the Collection class © Copyright, Macmillan Computer Publishing All rights reserved http://www.pbs.mcp.com/ebooks/1571691529/ape/ape.htm (7 of 7) [9/22/1999 2:25:40 AM] Visual Basic Database How-To Copyright Visual Basic Database How-To ©Copyright, Macmillan Computer Publishing All rights reserved No part of this book may be used or reproduced in any form or by any means, or stored in a database or retrieval system without prior written permission of the publisher except in the case of brief quotations embodied in critical articles and reviews For information, address Macmillan Publishing, 201 West 103rd Street, Indianapolis, IN 46290 This material is provided "as is" without any warranty of any kind © Copyright, Macmillan Computer Publishing All rights reserved http://www.pbs.mcp.com/ebooks/1571691529/copy.htm [9/22/1999 2:25:47 AM] ... reserved Visual Basic Database How-To Introduction Visual Basic Database How-To q About This Book q What You Need to Use This Book Introduction About This Book Since version 3, Visual Basic has... http://www.pbs.mcp.com/ebooks/157 169 1529/ch01/ch01.htm (37 of 37) [9/22/1999 1: 56: 54 AM] Visual Basic Database How-To Ch Accessing a Data-base with Data Access Objects Visual Basic Database How-To -2Accessing... Access database files delivered with Visual Basic (later chapters demonstrate how to create a database with Visual Basic) The techniques, however, apply to all the databases that Visual Basic