This tutorial provides a brief introduction to developing database applications with Visual Basic through a series of nine step

-by-step exercises. It should be noted that these exercises use the Data control with other controls bound to it. The Data control does a lot for you "behind the scenes" and you may be tempted to use it in your applications, but be advised that the Data control is rarely used in professional applications â¼³ the norm is to write your own database access code so that you have complete control over the process. These exercises are worthwhile in that you can see what data bound controls are all about, but again be advised that they should not be used for professional application development. For further information on why data bound controls are "evil", read this article.

The intrinsic Data control is geared toward MS-Access 97 and earlier databases, although a later VB service pack added connectivity for Access 2000 databases. These articles use the two sample Access databases provided with Visual Basic (BIBLIO.MDB and NWIND.MDB). These databases are provided in Access 97 format. On a default installation of VB6, these databases can be found in the folder: C:\Program Files\Microsoft Visual Studio\VB98. To do these exercises, you should make a folder into which you will copy the two database files mentioned above. Then, within the folder you have created, make separate subfolder for each exercise, one level below the root of your folder. The DatabaseName property for the Data control in these exercises assumes that the database file resides one directory level above the folder in which the exercise project files reside.

EXERCISE 1 Connecting to an Access Database Using the VB Data Control

STEPS: 1. Open a new Visual Basic project. 2. Put a data control (an intrinsic control, located in the VB toolbox) on the form and set the properties as follows: Property (Name) Caption Connect DatabaseName Value datAuthors Use the arrows to view the data Access (default) ..\biblio.mdb

DefaultType RecordSource

UseJet (default) Authors (choose from list)

Notes: When you use the Data Control in a project, the properties that must be set areDatabaseName and RecordSource, in that order. DatabaseName is the name of the database you want to use, and the RecordSource is the name of the table in that database that you want to use. 3. On your form, create a text box for each field in the Authors table, with labels. (If you were to open the database in Access, you would see that the three fields of the Authors table are Au_ID, Author, and Year Born.) Set the properties of the three textboxes as follows: Name txtAuthID txtAuthor txtYearBorn DataSource datAuthors datAuthors datAuthors DataField Au_ID Author Year Born

In addition, set the Enabled property of txtAuthID to False. When you want a control (such as a text box) to display data from a database, the properties that must be set are DataSource and Datafield. The DataSource is the name of the data control on the form (it should already be configured), and the DataField is the name of the particular field in the database that should be displayed in the control (this field will be in the table that was chosen for the RecordSource of the data control). At this point, your form should resemble the screen-shot below:

You can also invoke these methods through code. or last record. Move ahead. MovePrevious. STEPS: 1. EXERCISE 2 Using Navigation Buttons with a Data Control In the previous exercise. 2. Note that your changes remain in effect. then move back to the record you changed. Copy the files from Exercise #1 into a new folder and open the VBP file in the new folder. Set the Visible property of the data control (datAuthors) to False. Make four command buttons with the following properties: Name Caption cmdMoveNext Next Record cmdMoveLast Last Record cmdMovePrevious Previous Record cmdMoveFirst First Record At this point. Use the arrows on the data control to scroll through the data.4. 3. next. your form should resemble the screen-shot below: . Save and run the project. Note that this exercise demonstrated that you can create a simple but functional application that allows the user to browse through the rows of a database table (or result set) and to update rows in that table without writing any code. change the data in the author name or year born field. The data control automatically updates a record when you move off of the record. and MoveLast methods. MoveNext. previous. 5. On any record. you saw that by clicking specific buttons of the data control. which is what this exercise demonstrates. you could move to the first. What is happening is that the data control is automatically invoking specific methods of the recordset object: namely the MoveFirst.

.4. Put the following four lines of code in the appropriate Click events for the buttons: Event cmdMoveNext_Click cmdMoveLast_Click cmdMovePrevious_Click cmdMoveFirst_Click 5.Recordset.Recordset. STEPS: 1.MoveNext datAuthors.Recordset. 6. Save and run your program.Recordset.MovePrevious datAuthors. What happens? (We will fix this in Exercise 4.MoveLast datAuthors. Move to the last record and then click the Move Next button twice. BOF (Beginning Of File) is a Boolean property of the recordset object that becomes true when an attempt is made to move backward past the first record in a recordset. Copy the files from Exercise #1 into a new folder and open the VBP file in the new folder.) EXERCISE 3 Using the BOFAction and EOFAction Properties of the Data Control Code datAuthors.MoveFirst Note: EOF (End Of File) is a Boolean property of the recordset object that becomes true when an attempt is made to move forward past the last record in a recordset.

Type some data in all the fields (the author ID will be entered automatically). Verify that the data you entered is still in the database. Run the program and notice what happens when you use the arrows to â¼ movepreviousâ¼ when you are on the first record already. Move back to the last record to verify that your data is still there. then start it again. Note that this exercise demonstrated that you can create a simple but functional application that not only allows the user to browse through the rows of a database table and to update rows in that table. A blank record should appear. and set the data control properties as follows: BOFAction = 1 â¼³ BOF EOFAction = 1 â¼³ EOF Notice what happens to the arrows on the data control when you try to move past the last or first record. Click once on the data control and make sure that the following properties are set: BOFAction = 0 â¼³ Move First EOFAction = 0 â¼³ Move Last 3. 4. End the program. click the >| arrow on the data control to move to the end of the records. Now set the EOFAction property to 2 â¼³ AddNew. End the program. 6. 7. or â¼ movenextâ¼ when you are already on the last record. EXERCISE 4 Using the EOF and BOF Properties with Navigation Buttons STEPS: .2. then click on the > arrow to move to the next record (which does not exist). then move to a previous record. but also allows the user to add a new record to that table without writing any code. Run the program. 5.

which causes all the bound controls to be cleared so that the user can enter data.Recordset. Put the following code in the cmdMoveNext_Click() event: datAuthors.1. Updating and Deleting Records In previous exercises. and there is no next record. 4. by setting the EOFAction of the data control to "2 â¼³ AddNew". Put similar code in the cmdMovePrevious_Click() event.EOF = True Then datAuthors. 2. Copy the Exercise #4 files into a new folder and open the VBP file. The recordset object also has a Delete method. You also saw that. which can only be invoked through code â¼³ it cannot be accessed automatically through the data control.MoveLast. EXERCISE 5 Adding. you could use MoveFirst to let the user loop around to the first record. When the user clicks on the MoveNext button. and Delete methods of the recordset object through code.Recordset. In addition to being invoked automatically through the data control. 3. AddNew.MoveLast End If FYI: Instead of Recordset. you will be checking forRecordset. changes to a record are automatically updated when the user moves off of that record â¼³ this is the Update method of the recordset object of the data control at work. your code should stay on the same record (the last one). the data control will invoke the AddNew method of the recordset object. . STEPS: 1. the Update and AddNew methods can also be invoked through code. This exercise shows you how to invoke the Update. Copy the files from Exercise #2 into a new folder and open the VBP file in the new folder. you saw that with the data control.BOF = True. In this case.Recordset.MoveNext If datAuthors. Save and run the project and test it thoroughly.

When the user clicks on New Record.Enabled = False cmdMoveNext.AddNew cmdSaveRecord. Add three more buttons to the form and set their properties as follows: Name cmdNewRecord cmdSaveRecord cmdDeleteRecord Caption New Record Save Record Delete Record Enabled True False True Your form should resemble the following: 3.Recordset.2.Enabled = False cmdDeleteRecord. Save and run the program to make sure the buttons are enabled and disabled correctly.Enabled = False cmdMoveLast.Enabled = False cmdMovePrevious.Enabled = True cmdMoveFirst.Enabled = False cmdNewRecord. Put the following code in the cmdNewRecord_Click() event: datAuthors. . your program should enable the Save Data button and disable the others.Enabled = False 4.

Delete 'move to a valid record cmdMoveNext_Click Exit Sub .Recordset. When the user clicks on the Save button to save the data that was entered.Enabled = True cmdNewRecord. the program will crash. If the user attempted to update the record at that point.Enabled = True cmdMoveLast. Something to watch out for with the Delete method is that when a record is deleted. the Jet (Access) database engine will not allow the delete. _ "Confirm") = vbNo Then Exit Sub End If 'delete the current record datAuthors. in thecmdDelete_Click() event: On Error GoToDelete_Error If MsgBox("Are you sure you want to delete this record?".5. you should move the user to a valid record immediately following the delete. it is good programming practice to ask the user to confirm any destructive action. Finally.Enabled = False cmdMoveFirst.Recordset. Place the following code in thecmdSaveRecord_Click() event: datAuthors.Enabled = True 6.Update cmdSaveRecord. Another issue is that if you attempt to delete a record that has a related record in another table. _ vbQuestion + vbYesNo + vbDefaultButton2. the recordset is no longer pointing to a valid record. which addresses the above-mentioned issues.Enabled = True cmdDeleteRecord. the Update method should be called and the buttons should be redisplayed. Place the following code. a run-time error would occur.Enabled = True cmdMovePrevious. and a run-time error will occur.Enabled = True cmdMoveNext. If you don't trap the error. but the data from the deleted record still remains in the controls. To prevent this from happening.

) caused the Validate event to fire. if somewhere in your program you code the statement datAuthors.. This means that any code contained in the Validate event procedure will be executed prior to the execution of a statement containing one of these methods. The value of Action can be tested by comparing it to a literal integer value (1.) or with its corresponding VB predefined constant (vbDataActionMoveFirst. „y An Undo feature which will enable the user to cancel changes that they make to a record. as well as the CancelUpdate and UpdateControls methods of the data control. This exercise introduces the Validate event of the data control.). Error code = " _ &Err. (For example.mdb database . Unload. Save and test your program to make sure all functions work. Update.Delete_Error: ' This error will occur if you attempt to delete an author that is related to ' another table in the biblio. Save As Integer). etc. MsgBox "This record cannot be deleted.Number&vbCrLf&Err.Recordset. In addition. Delete. For example.Update. vbDataActionUpdate. etc. or setting of a Bookmark. The Action argument tells you which particular action (MoveFirst. EXERCISE 6 Using the Validate Event This exercise will add the following functionality to the form you created in Exercise 5: „y Validating the user's input when they update an existing record or add a new record to the database. the Validate event procedure header for this exercise will look like this: Private Sub datAuthors_Validate(Action As Integer.. and the DataChanged property of bound controls. The Validate event takes in two VB-provided arguments: Action and Save. any code in the Validate event will be executed first. the Bookmark and LastModified properties of the recordset object. whatever action triggered the Validate event can be cancelled if you set the value of Action to zero (or to the predefined constant vbDataActionCancel) prior to exiting the Validate event . when VB encounters this statement. etc. 2. The Validate event of the data control occurs prior to a record Move and prior to an Update. Close. "Cannot Delete" 7. _ vbCritical. 3.Description.

DataChanged Then If (something is wrong with txtMyField) Then MsgBox "Invalid data in this field" End If End If The CancelUpdate method is used to cancel any pending updates resulting from an Edit orAddNew operation. . This method is typically used to restore the contents of bound controls to their original values. DataChanged is a run-time only Boolean property available with data-bound controls (such as the textboxes you have been using). For example. You can set Save to False to prevent VB from saving changes to a record. The UpdateControls method gets the current record from a Data control's Recordset object and displays the appropriate data in controls bound to a Data control. as when a user makes changes to data and then decides to cancel the changes. if a user invokes the Edit or AddNew method and hasn't yet invoked the Update method. Similarly.procedure. CancelUpdate cancels any changes made after Edit or AddNew was invoked. typically used in the Validate event. You would typically use DataChanged as a first test to see if a particular field needs further validation (if the user did not change the data in a field. The values of Action and their corresponding predefined constants are as follows: Constant vbDataActionCancel vbDataActionMoveFirst vbDataActionMovePrevious vbDataActionMoveNext vbDataActionMoveLast vbDataActionAddNew vbDataActionUpdate vbDataActionDelete vbDataActionFind vbDataActionBookmark vbDataActionClose vbDataActionUnload Value 0 1 2 3 4 5 6 7 8 9 10 11 Description Cancel the operation when the Sub exits MoveFirst method MovePrevious method MoveNext method MoveLast method AddNew method Update operation (not UpdateRecord) Delete method Find method The Bookmark property has been set The Close method The form is being unloaded The Save argument is a Boolean value indicating whether or not bound data has changed. This method does not cause the Validate event to fire. why bother doing further validation on that field?) The logic structure would look something like the following: If txtMyField.

LastModified is a property of the Recordset object that returns a bookmark indicating the most recently added or changed record. STEPS: 1. If you assign the Bookmark value to a variable and then move to another record. your form should resemble the following: 3. 2. Place the following statements in the general declarations section of your form: . Place two new command buttons on your form and set their properties as follows: Name cmdUndo cmdCancelNew Caption Undo Cancel New Record Enabled True True At this point. Bookmark is a property of the Recordset object that contains a binary string identifying the current record. you can make the earlier record current again by setting the Bookmark property to that string variable.the UpdateRecord method (not used in this exercise) saves the current contents of bound controls to the database during the Validate event without triggering the Validate event again. Copy your files from Exercise 5 into a new folder.

Enabled = False cmdDeleteRecord. and disable the "Undo" button. not adding a record.Recordset.AddNew If blnValidationError Then Exit Sub cmdSaveRecord.Enabled = False cmdNewRecord. the code invokes the AddNew method. which consists of only one statement: datAuthors. and the user must correct the problem with the current record. Code the event procedure for the new cmdUndo button. In that case the error is flagged. Modify the cmdNewRecord_Click() event procedure to look like the following (new statements are shown in bold): datAuthors.Enabled = False cmdMoveLast. which will set the blnValidationError flag.Private blnAddingNewRecord As Boolean Private blnValidationError As Boolean 4. the AddNew is canceled. we enable the "Cancel New" button so that they can cancel the process. If everything's OK.Enabled = False blnAddingNewRecord = True Explanation When the user initiates the process to add a record.UpdateControls 5.Enabled = False cmdUndo. which will cause the Validate event to fire. 6. This will catch the case where the user has modified the current record (and has made errors) and then clicks the "New Record" button. which will be tested in the Validate event (shown in a few steps below).Enabled = True cmdMoveFirst.Enabled = False cmdMovePrevious. Modify the cmdSaveRecord_Click() event procedure to look like the following (new statements are shown in bold): .Enabled = False cmdMoveNext. because that is only applicable when the user is changing.Enabled = True cmdCancelNew. We also set the blnAddingNewRecord flag to true.

Therefore.Recordset. Otherwise.Recordset.Recordset.Bookmark = datAuthors. where we will set theblnValidationError flag. control resumes with the If statement.Recordset.Enabled = True cmdNewRecord.Enabled = True cmdMovePrevious.Enabled = True blnAddingNewRecord = False Explanation When the user initiates a save for a newly added record. the record that was current before you invoked the "New Record" operation would be displayed. .Enabled = False cmdCancelNew. because the AddNew method and subsequent Update method does not cause the newly added record to become the "current" record.Enabled = True cmdMoveNext. the Update method is invoked (with the statementdatAuthors. When the Validate event terminates.Enabled = True cmdUndo. and you would have to go to the last record to see the newly added record.Enabled = True cmdDeleteRecord.Update). which will let the user continue working on the current record to correct the problem.Enabled = True cmdMoveLast.Enabled = False cmdMoveFirst. This will cause the Validate event to fire.Recordset.datAuthors. where that flag is tested.LastModified causes the newly added record to become the current record.Update If blnValidationError Then Exit Sub ' make the new record the current record datAuthors. The statement datAuthors.Bookmark _ = datAuthors. If there is an error.LastModified cmdSaveRecord. we want to exit the sub early. without this statement.Recordset. This is necessary if you want to see the data for the new record on the form after you add it. if the flag is False. that means that all validation checks passed and we can continue on our merry way.

the cmdUndo button is enabled and the blnAddingNewRecord flag is set to False. If the user wants to cancel the adding of a new record. Save As Integer) If Action = vbDataActionBookmark Then Exit Sub If Action = vbDataActionDelete Then Exit Sub 'check to see if a valid author id is entered: If txtAuthor. Since Validate is the default procedure for a data control. the CancelUpdate method should be used. The code is shown below: Private Sub datAuthors_Validate(Action As Integer. or setting of a Bookmark.DataChangedOrblnAddingNewRecord Then If Trim$(txtAuthor) = "" Then MsgBox "Author name must be entered" txtAuthor.SetFocus GoToCancelValidateAction End If End If 'check to see if a valid year is entered If txtYearBorn. Unload. then the UpdateControls method is used to restore the controls on the form . Delete. Recall that this event fires prior to a record Move and prior to an Update. you can get the procedure header by double-clicking on the data control. Code the Click event procedure for the cmdCancelNew command button.DataChangedOrblnAddingNewRecord Then If Val(txtYearBorn) = 0 Then MsgBox "Invalid year" txtYearBorn. Code the Validate event procedure for the datAuthors data control. Close. the cmdCancelNew button is disabled. 7.Since this event completes the operation of adding a new record.SetFocus GoToCancelValidateAction End If End If blnValidationError = False Exit Sub CancelValidateAction: blnValidationError = True Action = vbDataActionCancel Save = False End Sub 8.

Enabled = False cmdMoveFirst.Enabled = True blnAddingNewRecord = False End Sub 9. run and test the program.FindFirst criteria where criteria is a string item consisting of a field name. you must use VB's string-handling functions (especially the "&" for concatenation) to get the desired results. The comparison operators that can be used are =. <=.CancelUpdate datAuthors. Make sure you understand what the code is doing. EXERCISE 7 Using the Find Methods The Recordset object has methods FindFirst. Save. It is essentially the same as a SQL WHERE clause without the word WHERE. FindNext. <>.Recordset.Enabled = True cmdDeleteRecord.Enabled = True cmdMovePrevious.Recordset. FindLast. You can use these to search for a particular record in the Recordset. that string must be enclosed in double quotes.Enabled = True cmdUndo. Between.to the values of the current record (the record that was displayed on the form prior to the initiation of the AddNew operation). and a value. Typically. .Enabled = True cmdMoveLast. and In. a relational (comparison) operator.Enabled = True cmdNewRecord. Like. >=. The value on the right-hand side of the comparison operator must conform to the following rules: string values must be enclosed in single quotes numeric values are not enclosed in quotes date values must be enclosed in #'s (pound signs) If the criteria is expressed in a literal string. >.Enabled = False cmdCancelNew.UpdateControls 'enable& disable the appropriate buttons cmdSaveRecord.Enabled = True cmdMoveNext. The syntax is datControl. <. The code is shown below: Private Sub cmdCancelNew_Click() 'cancel the AddNew datAuthors. and FindPrevious.

FindFirst "[Pay Rate] > 30000" „y For string values. the apostrophe embedded in the string will be interpreted as the end of the string and a syntax error will most likely result.Recordset.FindNext _ "DateOfBirth< #" & Format$(dtmBirthDay.Text = "Author" Then strQuote = "'" Else strQuote = "" txtCriteria.Recordset.Examples: datBooks.Text = Val(txtCriteria. "mm/dd/yyyy") & "#" In this exercise.FindFirst "ISBN = '123-456-789-0' " datMembers.FindNext "Amount > " &txtAmount. if there is the possibility that the search string will contain an apostrophe.Text& "'" The next example assumes that the variable dtmBirthDay is of the Date data type: datMembers.Recordset.Text& _ " "&strQuote&txtCriteria.FindNext "FirstName = '" &txtName. then enters the search value in a textbox.Recordset. The criteria for the Find methods are thus formed by statements similar to the following: If cboField.Text& " " &cboRelOp.Text&strQuote datAuthors.Text) End If strCriteria = _ cboField.Recordset. you must put square brackets around the field name.Text datMembers.Recordset. the user selects both the field name and the relational operator from combo boxes.FindNext "DateOfBirth< #1/1/1950#" datBooks. as in the following example: datBooks.FindNext "Amount > 100" datMembers. The easiest way to provide this "insurance" against embedded apostrophes is to use the .Recordset. an extra measure should be taken to "double" the apostrophes in the string â¼³ otherwise.Recordset.FindFirststrCriteria Additional Notes: „y If the name of the field in the database table has spaces in its name.

If a match is found. In this particular example. Copy the files from Exercise 6 into a new folder.. If you use a Find method and a record is not found. "''") & "'" For example. You should use this property to determine whether or not a record was found.Recordset. you simply coded "ProductName = '" &strSearchText& "'" for the criteria. then the NoMatch property is set to True. "'". if strSearchText contained "Chef Anton's Cajun Gumbo".e. NoMatch will be set to True. the criteria in the above statement would evaluate to ProductName = 'Chef Anton''s Cajun Gumbo' and the double apostrophe in "Anton''s" would be correctly interpreted by the SQL parser as a single apostrophe. the result would be ProductName = 'Chef Anton's Cajun Gumbo' which would result in an error: the SQL parser would interpret the criteria to be "Chef Anton" with extraneous characters ("s Cajun Gumbo") at the end. and the found record becomes the current record. It is set to False to begin with. STEPS: 1.FindFirst _ "ProductName = '" & Replace$(strSearchText. Follow steps 2 through 4 to get your form to resemble the following: . if the Replace function was NOT used (i.Replace$ function on the string in question to replace any occurrences of a single apostrophe with two apostrophes: datProducts. The Recordset has a NoMatch property.

Add four command buttons to the form and set their properties as follows: Name cmdFind cmdFindAgain cmdCancelFind cmdGo Caption F&ind Find &Again Cance&l Find &Go! Enabled True False False False 3. Name cboField Style 2 .Dropdown List Enabled False List Au_Id Author [Year Born] = > < >= <= cboRelOp False <> Like .Dropdown List 2 . Add two combo boxes and set their properties as follows (Note: you can set the List property of a listbox or combo box in the Properties box by typing in values and pressing Ctrl+Enter .2.this action is analogous to using the AddItem method in code).

which automatically invokes the Click event. To ensure that strBookmark always references the current record. Add a textbox called txtCriteria and set its Enabled property to False.SetFocus End If End Sub Private Sub cboRelOp_Click() If cboRelOp.SetFocus End If End Sub 7.4.Bookmark at the end of each of these event procedures: cmdMoveFirst_Click cmdMoveLast_Click cmdMoveNext_Click cmdMovePrevious_Click This is necessary to ensure that we have a pointer to a valid record available in case the Find method fails.List(0) 6. place this statement strBookmark = datAuthors. Code the Click events for the combo boxes (to provide smoother navigation for the user).Enabled Then txtCriteria. nor can it be invoked prior to completion of a Form Load. 8. Place the following statements in the Form_Load event: cboField. Private Sub cboField_Click() If cboField. SetFocus cannot be invoked on a disabled control.Text = cboRelOp.Enabled Then cboRelOp. which will normally perform a SetFocus.Recordset. The Enabled tests are necessary because the Form_Load event assigns the first element of the their respective List property arrays to their respective text properties. Place the following code in the cmdFind _Click event (disables navigating and updating controls and enables "Find" controls): blnFirstFind = True .Text = cboField. which leaves the current record pointer undefined. 5.List(0) cboRelOp.

txtAuthor.Bookmark = strBookmark .Enabled = False cmdUndo.Enabled = False cmdCancelNew.Enabled = True txtCriteria.Enabled = False cmdMoveFirst. Place the following code in the cmdGo_Click event (prepares criteria argument for the Find methods.Enabled = False cmdSaveRecord.FindFirststrCriteria Else .Enabled = False cmdCancelFind.Enabled = False cmdMoveLast.Enabled = True cmdGo.Enabled = True 9.Enabled = False txtYearBorn.Enabled = False cmdMovePrevious.Enabled = True cboRelOp.Text& " " &cboRelOp.Text = "Author" Then strQuote = "'" Else strQuote = "" txtCriteria = Val(txtCriteria) End If strCriteria = _ cboField.Enabled = False cmdDeleteRecord.Enabled = False cmdFind.Enabled = False cmdNewRecord.Recordset If blnFirstFind Then blnFirstFind = False . then performs the Find): Dim strQuote As String Dim strCriteria As String If cboField.Enabled = True cboField.Enabled = False cmdMoveNext.NoMatch Then MsgBox "Data not found" .FindNextstrCriteria End If If .Text& _ " "&strQuote&txtCriteria&strQuote With datAuthors.

Enabled = True cmdCancelFind.Enabled = True cmdMoveNext. and search strings.Enabled = False 12. relational operators.Enabled = True cmdDeleteRecord. Place the following code in the cmdCancelFind_Click() event (enables the navigation and updating controls.Enabled = True cmdUndo.Enabled = False cboField. .Enabled = True cmdCancelNew.Enabled = False End If End With 10. disables the Find controls): txtAuthor.Enabled = True cmdNewRecord.Enabled = False cmdGo.Enabled = False txtCriteria.Enabled = True cmdMovePrevious.Enabled = True cmdMoveLast.Enabled = False cboRelOp. place the following line (performs the same actions as the cmdGo_Click event): cmdGo_Click 11.cmdFind_Click cmdFindAgain.Enabled = True cmdSaveRecord.Enabled = True cmdFind.Enabled = True cboField. In the cmdFindAgain_Click event.Enabled = False cmdGo.Enabled = True cmdMoveFirst.Enabled = False txtCriteria.Enabled = False cboRelOp. Run the program and test the Find operations using different fields.Enabled = False Else cmdFindAgain.Enabled = True txtYearBorn.

\NWIND. . Follow the steps in this exercise to create a Categories and Products master/detail form similar to the screen-shot shown below: STEPS: 1.\NWIND. Place two data controls on the form and set their properties as follows: Name datCategories datProducts DatabaseName .MDB RecordSource Categories (leave blank) Visible True False Set the Caption property of datCategories to "Use Arrow Buttons to Navigate Records".EXERCISE 8 Using the MSFlexGrid Control The MSFlexGrid can be used to display multiple records in a grid..MDB . It cannot be used to edit data or add and delete records..

Place the following code in the datCategories_Reposition event: datProducts. as shown in the screen-shot. Set the DataSource property for each of these four controls todatCategories. If necessary. set its MultiLine property to True and set its ScrollBars property to 2 â¼³ Vertical. add the MSFlexGrid to your toolbox from the Components item of the Project menu. Place three textboxes and one OLE control on the form. For the Description text box.2.Refresh 6. Description. 4.RecordSource _ = "SELECT * FROM Products " _ & "WHERE CategoryID = " &txtCatID datProducts. as shown in the screen-shot. CategoryName. Add appropriate label controls to accompany the textboxes. 3. and will also trigger the Reposition event of the datCategories control. and Picturerespectively. and set its properties as follows: Property AllowUserResizing DataSource FixedCols Value 1 â¼³ flexResizeColumns datProducts 0 Enclose the grid in a frame. EXERCISE 9 . Place an MSFlexGrid control on your form.Refresh This will force the controls bound to datCategories to be populated sooner than they would otherwise.) 5. (The Reposition event of a data control occurs whenever a Move method is executed against that control. Set the Enabled property of the Category ID textbox to False. Set the DataField property for these controls to CategoryID. Save and run the program. Place the following line of code in the Form_Load event: datCategories. and group these four controls into a frame.

) „y Once you have installed the DBGrid control. DBGRID32.0 (SP3)") when you access the Components dialog by selecting Project|Components within VB. You should now see the control (under the name "Microsoft Data Bound Grid Control 5.REG. and delete records.OCX. but it is available on the VB 6/VS 6 CD. 5. update.OCX file by browsing to the folder in which you copied it previously. 3. All three files should be located in this folder:D:\COMMON\TOOLS\VB\CONTROLS (where "D:" is the drive letter of your CD-ROM drive). andDBGRID. proceed with the steps of Exercise 9: STEPS: 1. perform the following steps. „y Copy these three files to your Windows "System" directory (the default system directory varies depending on the OS being used: On Windows 2000 and NT the default is WINNT\SYSTEM32. you may download these three files here. 98.0. Place a DBGrid on your form in the position previously occupied by the flex grid.Using the DBGrid Control This exercise uses the DBGrid control. Locate these three files on your VB6 installation CD: DBGRID32.REG to register the DBGRID32. and on 95.OCX. „y Double-click on DBGRID. Property AllowAddNew AllowDelete AllowUpdate DataSource Copy your files from Exercise 8 to a new folder and open the project. If you cannot locate your installation CD.DEP. (If not. include the Microsoft Data Bound Grid Control. 4. and ME it is WINDOWS\SYSTEM). Set the DBGrid's properties as follows: Value True True True datProducts . on XP the default is WINDOWS\SYSTEM32. Out of Project | Components. 2. Delete the MSFlexGrid control. which goes a step further than the MSFlexGrid in that allows the user to add. The DBGrid control does not install automatically when you install Visual Basic 6. click on the â¼ Browse⼦⼠button in the Components dialog and locate the DBGRID32. To install the DBGrid control.

or deleting a record with a related record in another table). While this application is certainly not bullet-proof. changing a foreign key to a non-existent value. update. experiment by using the grid to add. Save and run the program.6. and delete records. . you'll find that built-in error-checking will prevent most "illegal" actions attempted by the user (such as trying to change the primary key. The code can remain as is.

Sign up to vote on this title
UsefulNot useful