29
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 Value (Name) datAuthors Caption Use the arrows to view the data Connect Access (default) DatabaseName ..\biblio.mdb DefaultType UseJet (default) RecordSource 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 DataSource DataField txtAuthID datAuthors Au_ID txtAuthor datAuthors Author txtYearBorn datAuthors Year Born In addition, set the Enabled property of txtAuthID to False .

VB Access Db

Embed Size (px)

DESCRIPTION

VB Access Db

Citation preview

EXERCISE 1Connecting to an Access Database Using the VBData ControlSTEPS: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:PropertyValue

(Name)datAuthors

CaptionUse the arrows to view the data

ConnectAccess(default)

DatabaseName..\biblio.mdb

DefaultTypeUseJet(default)

RecordSourceAuthors(choose from list)

Notes: When you use the Data Control in a project, the properties that must be set areDatabaseNameandRecordSource,in that order.DatabaseNameis the name of the database you want to use, and theRecordSourceis 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:NameDataSourceDataField

txtAuthIDdatAuthorsAu_ID

txtAuthordatAuthorsAuthor

txtYearBorndatAuthorsYear Born

In addition, set theEnabledproperty of txtAuthID toFalse.When you want a control (such as a text box) to display data from a database, the properties that must be set areDataSourceandDatafield. TheDataSourceis the name of the data control on the form (it should already be configured), and theDataFieldis 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:

4. Save and run the project. Use the arrows on the data control to scroll through the data.5. On any record, change the data in the author name or year born field. Move ahead, then move back to the record you changed. Note that your changes remain in effect. The data control automatically updates a record when you move off of the record.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.EXERCISE 2Using Navigation Buttons with a Data ControlIn the previous exercise, you saw that by clicking specific buttons of the data control, you could move to the first, previous, next, or last record. What is happening is that the data control is automatically invoking specific methods of the recordset object: namely theMoveFirst,MovePrevious,MoveNext, andMoveLastmethods. You can also invoke these methods through code, which is what this exercise demonstrates.STEPS:1.Copy the files from Exercise #1 into a new folder and open the VBP file in the new folder.2. Set theVisibleproperty of the data control (datAuthors) toFalse.3. Make four command buttons with the following properties:NameCaption

cmdMoveNextNext Record

cmdMoveLastLast Record

cmdMovePreviousPrevious Record

cmdMoveFirstFirst Record

At this point, your form should resemble the screen-shot below:

4. Put the following four lines of code in the appropriate Click events for the buttons:EventCode

cmdMoveNext_ClickdatAuthors.Recordset.MoveNext

cmdMoveLast_ClickdatAuthors.Recordset.MoveLast

cmdMovePrevious_ClickdatAuthors.Recordset.MovePrevious

cmdMoveFirst_ClickdatAuthors.Recordset.MoveFirst

5. Save and run your program.6. Move to the last record and then click theMove Nextbutton twice. What happens? (We will fix this in Exercise 4.)EXERCISE 3Using the BOFAction and EOFAction Propertiesof the Data ControlNote: 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.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.STEPS:1. Copy the files from Exercise #1 into a new folder and open the VBP file in the new folder.2.Click once on the data control and make sure that the following properties are set:BOFAction = 0 Move FirstEOFAction = 0 Move Last3. Run the program and notice what happens when you use the arrows to move previous when you are on the first record already, or move next when you are already on the last record.End the program, and set the data control properties as follows:BOFAction = 1 BOFEOFAction = 1 EOFNotice what happens to the arrows on the data control when you try to move past the last or first record.4. Now set theEOFActionproperty to2 AddNew.5. Run the program; click the>|arrow on the data control to move to the end of the records; then click on the > arrow to move to the next record (which does not exist).6. A blank record should appear. Type some data in all the fields (the author ID will be entered automatically), then move to a previous record. Move back to the last record to verify that your data is still there.7. End the program, then start it again. Verify that the data you entered is still in the database.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, but also allows the user to add a new record to that table without writing any code.EXERCISE 4Using the EOF and BOF Properties with Navigation ButtonsSTEPS:1. Copy the files from Exercise #2 into a new folder and open the VBP file in the new folder.2. When the user clicks on the MoveNext button, and there is no next record, your code should stay on the same record (the last one).Put the following code in thecmdMoveNext_Click()event:datAuthors.Recordset.MoveNextIf datAuthors.Recordset.EOF = True ThendatAuthors.Recordset.MoveLastEnd IfFYI: Instead ofRecordset.MoveLast, you could useMoveFirstto let the user loop around to the first record.3. Put similar code in thecmdMovePrevious_Click()event. In this case, you will be checking forRecordset.BOF = True.4. Save and run the project and test it thoroughly.EXERCISE 5Adding, Updating and Deleting RecordsIn previous exercises, you saw that with the data control, changes to a record are automatically updated when the user moves off of that record this is theUpdatemethod of the recordset object of the data control at work. You also saw that, by setting the EOFAction of the data control to "2 AddNew", the data control will invoke theAddNewmethod of the recordset object, which causes all the bound controls to be cleared so that the user can enter data. In addition to being invoked automatically through the data control, the Update and AddNew methods can also be invoked through code. The recordset object also has aDeletemethod, which can only be invoked through code it cannot be accessed automatically through the data control.This exercise shows you how to invoke the Update, AddNew, and Delete methods of the recordset object through code.STEPS:1. Copy the Exercise #4 files into a new folder and open the VBP file.2. Add three more buttons to the form and set their properties as follows:NameCaptionEnabled

cmdNewRecordNewRecordTrue

cmdSaveRecordSave RecordFalse

cmdDeleteRecordDelete RecordTrue

Your form should resemble the following:

3.When the user clicks onNew Record, your program should enable theSave Databutton and disable the others. Put the following code in thecmdNewRecord_Click()event:datAuthors.Recordset.AddNewcmdSaveRecord.Enabled = TruecmdMoveFirst.Enabled = FalsecmdMoveLast.Enabled = FalsecmdMovePrevious.Enabled = FalsecmdMoveNext.Enabled = FalsecmdDeleteRecord.Enabled = FalsecmdNewRecord.Enabled = False4. Save and run the program to make sure the buttons are enabled and disabled correctly.5. When the user clicks on the Save button to save the data that was entered, the Update method should be called and the buttons should be redisplayed. Place the following code in thecmdSaveRecord_Click()event:datAuthors.Recordset.UpdatecmdSaveRecord.Enabled = FalsecmdMoveFirst.Enabled = TruecmdMoveLast.Enabled = TruecmdMovePrevious.Enabled = TruecmdMoveNext.Enabled = TruecmdDeleteRecord.Enabled = TruecmdNewRecord.Enabled = True6.Something to watch out for with the Delete method is that when a record is deleted, the recordset is no longer pointing to a valid record, but the data from the deleted record still remains in the controls. If the user attempted to update the record at that point, a run-time error would occur. To prevent this from happening, you should move the user to a valid record immediately following the delete.Another issue is that if you attempt to delete a record that has a related record in another table, the Jet (Access) database engine will not allow the delete, and a run-time error will occur. If you don't trap the error, the program will crash.Finally, it is good programming practice to ask the user to confirm any destructive action.Place the following code, which addresses the above-mentioned issues, in thecmdDelete_Click()event:On Error GoTo Delete_ErrorIf MsgBox("Are you sure you want to delete this record?", _vbQuestion + vbYesNo + vbDefaultButton2, _"Confirm") = vbNo ThenExit SubEnd If'delete the current recorddatAuthors.Recordset.Delete'move to a valid recordcmdMoveNext_ClickExit SubDelete_Error:' This error will occur if you attempt to delete an author that is related to' another table in the biblio.mdb database ...MsgBox "This record cannot be deleted. Error code = " _& Err.Number & vbCrLf & Err.Description, _vbCritical, "Cannot Delete"7. Save and test your program to make sure all functions work.EXERCISE 6Using the Validate EventThis exercise will add the following functionality to the form you created in Exercise 5:Validating the user's input when they update an existing record or add a new record to the database.An Undo feature which will enable the user to cancel changes that they make to a record.This exercise introduces the Validate event of the data control, as well as the CancelUpdate and UpdateControls methods of the data control, the Bookmark and LastModified properties of the recordset object, and the DataChanged property of bound controls.TheValidateevent of the data control occurs prior to a record Move and prior to an Update, Delete, Unload, Close, or setting of a Bookmark. 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. For example, if somewhere in your program you code the statementdatAuthors.Recordset.Update, when VB encounters this statement, any code in the Validate event will be executedfirst.The Validate event takes in two VB-provided arguments: Action and Save. (For example, the Validate event procedure header for this exercise will look like this:Private Sub datAuthors_Validate(Action As Integer, Save As Integer).The Action argument tells you which particular action (MoveFirst, Update, etc.) caused the Validate event to fire. The value of Action can be tested by comparing it to a literal integer value (1, 2, 3, etc.) or with its corresponding VB predefined constant (vbDataActionMoveFirst, vbDataActionUpdate, etc.). In addition, 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 procedure. The values of Action and their corresponding predefined constants are as follows:ConstantValueDescription

vbDataActionCancel0Cancel the operation when the Sub exits

vbDataActionMoveFirst1MoveFirst method

vbDataActionMovePrevious2MovePrevious method

vbDataActionMoveNext3MoveNext method

vbDataActionMoveLast4MoveLast method

vbDataActionAddNew5AddNew method

vbDataActionUpdate6Update operation (not UpdateRecord)

vbDataActionDelete7Delete method

vbDataActionFind8Find method

vbDataActionBookmark9The Bookmark property has been set

vbDataActionClose10The Close method

vbDataActionUnload11The form is being unloaded

The Save argument is a Boolean value indicating whether or not bound data has changed. You can set Save to False to prevent VB from saving changes to a record.DataChangedis a run-time only Boolean property available with data-bound controls (such as the textboxes you have been using), 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, why bother doing further validation on that field?) The logic structure would look something like the following:If txtMyField.DataChanged ThenIf (something is wrong with txtMyField) ThenMsgBox "Invalid data in this field"End IfEnd IfTheCancelUpdatemethod is used to cancel any pending updates resulting from an Edit or AddNew operation. For example, if a user invokes the Edit or AddNew method and hasn't yet invoked the Update method, CancelUpdate cancels any changes made after Edit or AddNew was invoked.TheUpdateControlsmethod gets the current record from a Data control's Recordset object and displays the appropriate data in controls bound to a Data control. This method is typically used to restore the contents of bound controls to their original values, as when a user makes changes to data and then decides to cancel the changes. This method doesnotcause the Validate event to fire. Similarly, theUpdateRecordmethod (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.Bookmarkis a property of the Recordset object that contains a binary string identifying the current record. If you assign the Bookmark value to a variable and then move to another record, you can make the earlier record current again by setting the Bookmark property to that string variable.LastModifiedis a property of the Recordset object that returns a bookmark indicating the most recently added or changed record.STEPS:1.Copy your files from Exercise 5 into a new folder.2.Place two new command buttons on your form and set their properties as follows:NameCaptionEnabled

cmdUndoUndoTrue

cmdCancelNewCancel New RecordTrue

At this point, your form should resemble the following:

3.Place the following statements in the general declarations section of your form:Private blnAddingNewRecord As BooleanPrivate blnValidationError As Boolean4.Code the event procedure for the newcmdUndobutton, which consists of only one statement:datAuthors.UpdateControls5. Modify thecmdNewRecord_Click()event procedure to look like the following (new statements are shown in bold):datAuthors.Recordset.AddNewIf blnValidationError Then Exit SubcmdSaveRecord.Enabled = TruecmdCancelNew.Enabled = TruecmdMoveFirst.Enabled = FalsecmdMoveLast.Enabled = FalsecmdMovePrevious.Enabled = FalsecmdMoveNext.Enabled = FalsecmdDeleteRecord.Enabled = FalsecmdNewRecord.Enabled = FalsecmdUndo.Enabled = FalseblnAddingNewRecord = TrueExplanationWhen the user initiates the process to add a record, the code invokes the AddNew method, which will cause the Validate event to fire, which will set the blnValidationError flag. This will catch the case where the user has modified the current record (and has made errors) and then clicks the "New Record" button. In that case the error is flagged, the AddNew is canceled, and the user must correct the problem with the current record.If everything's OK, we enable the "Cancel New" button so that they can cancel the process, and disable the "Undo" button, because that is only applicable when the user is changing, not adding a record. We also set the blnAddingNewRecord flag to true, which will be tested in the Validate event (shown in a few steps below).6. Modify thecmdSaveRecord_Click()event procedure to look like the following (new statements are shown in bold):datAuthors.Recordset.UpdateIf blnValidationError Then Exit Sub' make the new record the current recorddatAuthors.Recordset.Bookmark _= datAuthors.Recordset.LastModifiedcmdSaveRecord.Enabled = FalsecmdCancelNew.Enabled = FalsecmdMoveFirst.Enabled = TruecmdMoveLast.Enabled = TruecmdMovePrevious.Enabled = TruecmdMoveNext.Enabled = TruecmdDeleteRecord.Enabled = TruecmdNewRecord.Enabled = TruecmdUndo.Enabled = TrueblnAddingNewRecord = FalseExplanationWhen the user initiates a save for a newly added record, the Update method is invoked (with the statementdatAuthors.Recordset.Update). This will cause the Validate event to fire, where we will set theblnValidationErrorflag. When the Validate event terminates, control resumes with the If statement, where that flag is tested. If there is an error, we want to exit the sub early, which will let the user continue working on the current record to correct the problem. Otherwise, if the flag is False, that means that all validation checks passed and we can continue on our merry way.The statementdatAuthors.Recordset.Bookmark = datAuthors.Recordset.LastModifiedcauses the newly added record to become the current record. This is necessary if you want to see the data for the new record on the form after you add it, because the AddNew method and subsequent Update method doesnotcause the newly added record to become the "current" record. Therefore, without this statement, the record that was current before you invoked the "New Record" operation would be displayed, and you would have to go to the last record to see the newly added record.Since this event completes the operation of adding a new record, the cmdCancelNew button is disabled, the cmdUndo button is enabled and the blnAddingNewRecord flag is set to False.7. Code the Validate event procedure for the datAuthors data control. Recall that this event fires prior to a record Move and prior to an Update, Delete, Unload, Close, or setting of a Bookmark. Since Validate is the default procedure for a data control, you can get the procedure header by double-clicking on the data control. The code is shown below:Private Sub datAuthors_Validate(Action As Integer, Save As Integer)If Action = vbDataActionBookmark Then Exit SubIf Action = vbDataActionDelete Then Exit Sub'check to see if a valid author id is entered:If txtAuthor.DataChanged Or blnAddingNewRecord ThenIf Trim$(txtAuthor) = "" ThenMsgBox "Author name must be entered"txtAuthor.SetFocusGoTo CancelValidateActionEnd IfEnd If'check to see if a valid year is enteredIf txtYearBorn.DataChanged Or blnAddingNewRecord ThenIf Val(txtYearBorn) = 0 ThenMsgBox "Invalid year"txtYearBorn.SetFocusGoTo CancelValidateActionEnd IfEnd IfblnValidationError = FalseExit SubCancelValidateAction:blnValidationError = TrueAction = vbDataActionCancelSave = FalseEnd Sub8. Code the Click event procedure for the cmdCancelNew command button. If the user wants to cancel the adding of a new record, the CancelUpdate method should be used; then the UpdateControls method is used to restore the controls on the form to the values of the current record (the record that was displayed on the form prior to the initiation of the AddNew operation). The code is shown below:Private Sub cmdCancelNew_Click()'cancel the AddNewdatAuthors.Recordset.CancelUpdatedatAuthors.UpdateControls'enable & disable the appropriate buttonscmdSaveRecord.Enabled = FalsecmdCancelNew.Enabled = FalsecmdMoveFirst.Enabled = TruecmdMoveLast.Enabled = TruecmdMovePrevious.Enabled = TruecmdMoveNext.Enabled = TruecmdDeleteRecord.Enabled = TruecmdNewRecord.Enabled = TruecmdUndo.Enabled = TrueblnAddingNewRecord = FalseEnd Sub9. Save, run and test the program. Make sure you understand what the code is doing.EXERCISE 7Using the Find MethodsThe Recordset object has methodsFindFirst, FindLast, FindNext,andFindPrevious. You can use these to search for a particular record in the Recordset.The syntax isdatControl.Recordset.FindFirstcriteriawherecriteriais a string item consisting of a field name, a relational (comparison) operator, and a value. It is essentially the same as a SQL WHERE clause without the word WHERE. The comparison operators that can be used are=,>,=,