visual basic application programs
TRANSCRIPT
-
7/27/2019 Visual Basic Application Programs
1/34
ENROLL: 110370111111 V.B.A EC-5TH/B
Practical 11
Aim: Write a program to perform addition of two matrices.
Public Sub matrix()
Dim a(3, 3) As IntegerDim b(3, 3) As IntegerDim c(3, 3) As IntegerDim i As IntegerDim j As IntegerDim k As IntegerDim l As IntegerDim m As Integerk = 3l = 8m = 14
For i = 1 To 3k = k + 1For j = 1 To 3a(i, j) = InputBox(" enter first matrix", a(i, j))Cells(k, j + 1) = a(i, j)Next jNext i
For i = 1 To 3l = l + 1
For j = 1 To 3b(i, j) = InputBox(" enter second matrix", b(i, j))Cells(l, j + 1) = b(i, j)Next jNext i
For i = 1 To 3For j = 1 To 3c(i, j) = a(i, j) + b(i, j)Next jNext i
For i = 1 To 3m = m + 1For j = 1 To 3Cells(m, j + 1) = c(i, j)Next jNext iEnd Sub
NAME: Page 1
-
7/27/2019 Visual Basic Application Programs
2/34
ENROLL: 110370111111 V.B.A EC-5TH/B
Output:
NAME: Page 2
-
7/27/2019 Visual Basic Application Programs
3/34
ENROLL: 110370111111 V.B.A EC-5TH/B
NAME: Page 3
-
7/27/2019 Visual Basic Application Programs
4/34
ENROLL: 110370111111 V.B.A EC-5TH/B
Practical : 12
Write a program in VBA to perform arithmetic operations using
functions and procedures.
Public Sub main()Dim i As IntegerDim j As Integeri = InputBox("Enter the value", i)j = InputBox("Enter the value", j)Call ADDITION(i, j)Call MINUS(i, j)Call MULTIPLICATION(i, j)Call DIVISION(i, j)End Sub
Public Sub ADDITION(i As Integer, j As Integer)Dim a As Integera = i + jCells(1, 2).Value = aEnd Sub
Public Sub MINUS(i As Integer, j As Integer)Dim m As Integer
m = i - jCells(2, 2).Value = mEnd Sub
Public Sub MULTIPLICATION(i As Integer, j As Integer)Dim o As Integero = i * jCells(3, 2).Value = oEnd Sub
Public Sub DIVISION(i As Integer, j As Integer)Dim d As Integerd = i / jCells(4, 2).Value = dEnd Sub
NAME: Page 4
-
7/27/2019 Visual Basic Application Programs
5/34
ENROLL: 110370111111 V.B.A EC-5TH/B
Output:
NAME: Page 5
-
7/27/2019 Visual Basic Application Programs
6/34
ENROLL: 110370111111 V.B.A EC-5TH/B
NAME: Page 6
-
7/27/2019 Visual Basic Application Programs
7/34
ENROLL: 110370111111 V.B.A EC-5TH/B
Practical 13
Aim: Write a program to perform Database connectivity
EXERCISE 1
Connecting to an Access Database Using the VB Data 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 theproperties as follows:
Property Value(Name) datAuthorsCaption Use the arrows to view the dataConnect Access (default)DatabaseName ..\biblio.mdbDefaultType 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 youwant 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 toopen 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 DataFieldtxtAuthID datAuthors Au_IDtxtAuthor datAuthors Author txtYearBorn datAuthors 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 thatmust be set are DataSource and Datafield. The DataSource is the name of the data control on theform (it should already be configured), and the DataField is the name of the particular field in the
NAME: Page 7
-
7/27/2019 Visual Basic Application Programs
8/34
ENROLL: 110370111111 V.B.A EC-5TH/B
database that should be displayed in the control (this field will be in the table that was chosen forthe 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 moveback to the record you changed. Note that your changes remain in effect. The data controlautomatically updates a record when you move off of the record.Note that this exercise demonstrated that you can create a simple but functional application thatallows the user to browse through the rows of a database table (or result set) and to update rowsin that table without writing any code.
NAME: Page 8
-
7/27/2019 Visual Basic Application Programs
9/34
ENROLL: 110370111111 V.B.A EC-5TH/B
EXERCISE 2
Using Navigation Buttons with a Data ControlIn the previous exercise, you saw that by clicking specific buttons of the data control, you couldmove 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 the MoveFirst,MovePrevious, MoveNext, and MoveLast methods. You can also invoke these methods throughcode, which is what this exercise demonstrates.STEPS:1. Copy the files from Exercise #1 into a new folder and open the VBP file in thenew folder.2. Set the Visible property of the data control (datAuthors) to False.
3. Make four command buttons with the following properties:
Name CaptioncmdMoveNext Next RecordcmdMoveLast Last RecordcmdMovePrevious Previous RecordcmdMoveFirst First 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:
Event Code
NAME: Page 9
-
7/27/2019 Visual Basic Application Programs
10/34
ENROLL: 110370111111 V.B.A EC-5TH/B
cmdMoveNext_Click datAuthors.Recordset.MoveNextcmdMoveLast_Click datAuthors.Recordset.MoveLastcmdMovePrevious_Click datAuthors.Recordset.MovePreviouscmdMoveFirst_Click datAuthors.Recordset.MoveFirst
5. Save and run your program.6. Move to the last record and then click the Move Next button twice. What happens? (We willfix this in Exercise 4.)
NAME: Page 10
-
7/27/2019 Visual Basic Application Programs
11/34
ENROLL: 110370111111 V.B.A EC-5TH/B
EXERCISE 3
Using the BOFAction and EOFAction Properties of the Data ControlNote: EOF (End Of File) is a Boolean property of the recordset object that becomes true when anattempt 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 whenan 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 previouswhen you are on the first record already, or move next when you are already on the lastrecord.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 firstrecord.4. Now set the EOFAction property to 2 AddNew.5. Run the program; click the >| arrow on the data control to move to the end of the records; thenclick 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 enteredautomatically), then move to a previous record. Move back to the last record to verify that yourdata is still there.7. End the program, then start it again. Verify that the data you entered is still in the database.
NAME: Page 11
-
7/27/2019 Visual Basic Application Programs
12/34
ENROLL: 110370111111 V.B.A EC-5TH/B
Note that this exercise demonstrated that you can create a simple but functional application thatnot only allows the user to browse through the rows of a database table and to update rows inthat table, but also allows the user to add a new record to that table without writing any code.
NAME: Page 12
-
7/27/2019 Visual Basic Application Programs
13/34
ENROLL: 110370111111 V.B.A EC-5TH/B
EXERCISE 4
Using 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 shouldstay on the same record (the last one).Put the following code in the cmdMoveNext_Click() event:datAuthors.Recordset.MoveNextIf datAuthors.Recordset.EOF = True Then
datAuthors.Recordset.MoveLastEnd If
FYI: Instead of Recordset.MoveLast, you could use MoveFirst to let the user loop around to thefirst record.3. Put similar code in the cmdMovePrevious_Click() event. In this case, you will be checking forRecordset.BOF = True.
4. Save and run the project and test it thoroughly.
NAME: Page 13
-
7/27/2019 Visual Basic Application Programs
14/34
ENROLL: 110370111111 V.B.A EC-5TH/B
EXERCISE 5
Adding, Updating and Deleting RecordsIn previous exercises, you saw that with the data control, changes to a record are automaticallyupdated when the user moves off of that record this is the Update method of the recordset
object of the data control at work. You also saw that, by setting the EOFAction of the datacontrol to "2 AddNew", the data control will invoke the AddNew method of the recordsetobject, which causes all the bound controls to be cleared so that the user can enter data. Inaddition to being invoked automatically through the data control, the Update and AddNewmethods can also be invoked through code. The recordset object also has a Delete method, whichcan only be invoked through code it cannot be accessed automatically through the datacontrol.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:
Name Caption EnabledcmdNewRecord New Record True
cmdSaveRecord Save Record FalsecmdDeleteRecord Delete Record True
Your form should resemble the following:
NAME: Page 14
-
7/27/2019 Visual Basic Application Programs
15/34
ENROLL: 110370111111 V.B.A EC-5TH/B
3. When the user clicks on New Record, your program should enable the Save Databutton and disable the others. Put the following code in the cmdNewRecord_Click() event:datAuthors.Recordset.AddNewcmdSaveRecord.Enabled = TruecmdMoveFirst.Enabled = FalsecmdMoveLast.Enabled = FalsecmdMovePrevious.Enabled = FalsecmdMoveNext.Enabled = FalsecmdDeleteRecord.Enabled = False
cmdNewRecord.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 methodshould be called and the buttons should be redisplayed. Place the following code in thecmdSaveRecord_Click() event:datAuthors.Recordset.UpdatecmdSaveRecord.Enabled = False
cmdMoveFirst.Enabled = TruecmdMoveLast.Enabled = TruecmdMovePrevious.Enabled = TruecmdMoveNext.Enabled = TruecmdDeleteRecord.Enabled = TruecmdNewRecord.Enabled = True
NAME: Page 15
-
7/27/2019 Visual Basic Application Programs
16/34
ENROLL: 110370111111 V.B.A EC-5TH/B
6. 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 stillremains in the controls. If the user attempted to update the record at that point, a run-time errorwould occur. To prevent this from happening, you should move the user to a valid recordimmediately 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 youdon'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 the cmdDelete_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 record
datAuthors.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.
NAME: Page 16
-
7/27/2019 Visual Basic Application Programs
17/34
ENROLL: 110370111111 V.B.A EC-5TH/B
EXERCISE 6
Using 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 arecord.This exercise introduces the Validate event of the data control, as well as the CancelUpdate andUpdateControls methods of the data control, the Bookmark and LastModified properties of therecordset object, and the DataChanged property of bound controls.The Validate event 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 theValidate event procedure will be executed prior to the execution of a statement containing one ofthese methods. For example, if somewhere in your program you code the statementdatAuthors.Recordset.Update, when VB encounters this statement, any code in the Validateevent will be executed first.
The Validate event takes in two VB-provided arguments: Action and Save. (For example, theValidate 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 theValidate 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 becancelled if you set the value of Action to zero (or to the predefined constantvbDataActionCancel) prior to exiting the Validate event procedure. The values of Action andtheir corresponding predefined constants are as follows:
Constant Value DescriptionvbDataActionCancel 0 Cancel the operation when the Sub exitsvbDataActionMoveFirst 1 MoveFirst methodvbDataActionMovePrevious 2 MovePrevious methodvbDataActionMoveNext 3 MoveNext methodvbDataActionMoveLast 4 MoveLast methodvbDataActionAddNew 5 AddNew methodvbDataActionUpdate 6 Update operation (not UpdateRecord)
NAME: Page 17
-
7/27/2019 Visual Basic Application Programs
18/34
ENROLL: 110370111111 V.B.A EC-5TH/B
vbDataActionDelete 7 Delete methodvbDataActionFind 8 Find methodvbDataActionBookmark 9 The Bookmark property has been setvbDataActionClose 10 The Close methodvbDataActionUnload 11 The form is being unloaded
The Save argument is a Boolean value indicating whether or not bound data has changed. Youcan set Save to False to prevent VB from saving changes to a record.DataChanged is a run-time only Boolean property available with data-bound controls (such asthe textboxes you have been using), typically used in the Validate event. You would typicallyuse DataChanged as a first test to see if a particular field needs further validation (if the user didnot change the data in a field, why bother doing further validation on that field?) The logicstructure would look something like the following:If txtMyField.DataChanged ThenIf (something is wrong with txtMyField) ThenMsgBox "Invalid data in this field"End IfEnd IfThe CancelUpdate method is used to cancel any pending updates resulting from an Edit orAddNew operation. For example, if a user invokes the Edit or AddNew method and hasn't yetinvoked the Update method, CancelUpdate cancels any changes made after Edit or AddNew was
invoked.The UpdateControls method gets the current record from a Data control's Recordset object anddisplays the appropriate data in controls bound to a Data control. This method is typically used torestore the contents of bound controls to their original values, as when a user makes changes todata and then decides to cancel the changes. This method does not cause the Validate event tofire. Similarly, the UpdateRecord method (not used in this exercise) saves the current contents ofbound controls to the database during the Validate event without triggering the Validate eventagain.
Bookmark is a property of the Recordset object that contains a binary string identifying thecurrent 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 stringvariable.LastModified is a property of the Recordset object that returns a bookmark indicating the mostrecently added or changed record.
NAME: Page 18
-
7/27/2019 Visual Basic Application Programs
19/34
ENROLL: 110370111111 V.B.A EC-5TH/B
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:
Name Caption EnabledcmdUndo Undo TruecmdCancelNew Cancel New Record True
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 new cmdUndo button, which consists of only onestatement:datAuthors.UpdateControls
NAME: Page 19
-
7/27/2019 Visual Basic Application Programs
20/34
ENROLL: 110370111111 V.B.A EC-5TH/B
5. Modify the cmdNewRecord_Click() event procedure to look like the following (newstatements are shown in bold):
datAuthors.Recordset.AddNewIf blnValidationError Then Exit Sub
cmdSaveRecord.Enabled = TruecmdCancelNew.Enabled = TruecmdMoveFirst.Enabled = FalsecmdMoveLast.Enabled = FalsecmdMovePrevious.Enabled = FalsecmdMoveNext.Enabled = FalsecmdDeleteRecord.Enabled = False
cmdNewRecord.Enabled = FalsecmdUndo.Enabled = FalseblnAddingNewRecord = TrueExplanationWhen the user initiates the process to add a record, the code invokes the AddNew method, whichwill cause the Validate event to fire, which will set the blnValidationError flag. This will catchthe 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, anddisable the "Undo" button, because that is only applicable when the user is changing, not addinga record. We also set the blnAddingNewRecord flag to true, which will be tested in the Validateevent (shown in a few steps below).6. Modify the cmdSaveRecord_Click() event procedure to look like the following (newstatements are shown in bold):datAuthors.Recordset.UpdateIf blnValidationError Then Exit Sub' make the new record the current recorddatAuthors.Recordset.Bookmark _= datAuthors.Recordset.LastModifiedcmdSaveRecord.Enabled = False
NAME: Page 20
-
7/27/2019 Visual Basic Application Programs
21/34
ENROLL: 110370111111 V.B.A EC-5TH/B
cmdCancelNew.Enabled = FalsecmdMoveFirst.Enabled = TruecmdMoveLast.Enabled = TruecmdMovePrevious.Enabled = True
cmdMoveNext.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
statement datAuthors.Recordset.Update). This will cause the Validate event to fire, where wewill set the blnValidationError flag. When the Validate event terminates, control resumes withthe If statement, where that flag is tested. If there is an error, we want to exit the sub early, whichwill let the user continue working on the current record to correct the problem. Otherwise, if theflag 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 seethe data for the new record on the form after you add it, because the AddNew method and
subsequent Update method does not cause 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 seethe newly added record.Since this event completes the operation of adding a new record, the cmdCancelNew button isdisabled, 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 firesprior 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 bydouble-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:
NAME: Page 21
-
7/27/2019 Visual Basic Application Programs
22/34
ENROLL: 110370111111 V.B.A EC-5TH/B
If txtAuthor.DataChanged Or blnAddingNewRecord ThenIf Trim$(txtAuthor) = "" ThenMsgBox "Author name must be entered"txtAuthor.SetFocusGoTo CancelValidateAction
End 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 If
End IfblnValidationError = FalseExit SubCancelValidateAction:blnValidationError = TrueAction = vbDataActionCancelSave = FalseEnd Sub
8. Code the Click event procedure for the cmdCancelNew command button. If the user wants tocancel the adding of a new record, the CancelUpdate method should be used; then theUpdateControls method is used to restore the controls on the form to the values of the currentrecord (the record that was displayed on the form prior to the initiation of the AddNewoperation). 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 = True
NAME: Page 22
-
7/27/2019 Visual Basic Application Programs
23/34
ENROLL: 110370111111 V.B.A EC-5TH/B
cmdDeleteRecord.Enabled = TruecmdNewRecord.Enabled = TruecmdUndo.Enabled = TrueblnAddingNewRecord = FalseEnd Sub
9. Save, run and test the program. Make sure you understand what the code is doing.
NAME: Page 23
-
7/27/2019 Visual Basic Application Programs
24/34
ENROLL: 110370111111 V.B.A EC-5TH/B
EXERCISE 7
Using the Find MethodsThe Recordset object has methods FindFirst, FindLast, FindNext, and FindPrevious. You can usethese to search for a particular record in the Recordset.
The syntax isdatControl.Recordset.FindFirst criteriawhere criteria is a string item consisting of a field name, a relational (comparison) operator, anda value. It is essentially the same as a SQL WHERE clause without the word WHERE. Thecomparison operators that can be used are =, >, =,
-
7/27/2019 Visual Basic Application Programs
25/34
ENROLL: 110370111111 V.B.A EC-5TH/B
strCriteria = _cboField.Text & " " & cboRelOp.Text & _" " & strQuote & txtCriteria.Text & strQuotedatAuthors.Recordset.FindFirst strCriteria
Additional Notes: If the name of the field in the database table has spaces in its name, you must putsquare brackets around the field name, as in the following example:datBooks.Recordset.FindFirst "[Pay Rate] > 30000" For string values, if there is the possibility that the search string will contain anapostrophe, an extra measure should be taken to "double" the apostrophes in the string
otherwise, the apostrophe embedded in the string will be interpreted as the end of the string and asyntax error will most likely result. The easiest way to provide this "insurance" againstembedded apostrophes is to use the Replace$ function on the string in question to replace anyoccurrences of a single apostrophe with two apostrophes:datProducts.Recordset.FindFirst _"ProductName = '" & Replace$(strSearchText, "'", "''") & "'"For example, if strSearchText contained "Chef Anton's Cajun Gumbo", the criteria in the abovestatement 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 asingle apostrophe.In this particular example, if the Replace function was NOT used (i.e., you simply coded"ProductName = '" & strSearchText & "'"for the criteria, the result would beProductName = '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.The Recordset has a NoMatch property. It is set to False to begin with. If you use a Find methodand a record is not found, then the NoMatch property is set to True. You should use this propertyto determine whether or not a record was found. If a match is found, NoMatch will be set toTrue, and the found record becomes the current record.
STEPS:
NAME: Page 25
-
7/27/2019 Visual Basic Application Programs
26/34
ENROLL: 110370111111 V.B.A EC-5TH/B
1. Copy the files from Exercise 6 into a new folder. Follow steps 2 through 4 to getyour form to resemble the following:
2. Add four command buttons to the form and set their properties as follows:
Name Caption Enabled
cmdFind F&ind TruecmdFindAgain Find &Again FalsecmdCancelFind Cance&l Find FalsecmdGo &Go! False
3. Add two combo boxes and set their properties as follows (Note: you can set the List propertyof a listbox or combo box in the Properties box by typing in values and pressing Ctrl+Enter - thisaction is analogous to using the AddItem method in code).
Name Style Enabled ListcboField 2 - Dropdown List False Au_Id
Author[Year Born]
cboRelOp 2 - Dropdown List False =>=
NAME: Page 26
-
7/27/2019 Visual Basic Application Programs
27/34
ENROLL: 110370111111 V.B.A EC-5TH/B
-
7/27/2019 Visual Basic Application Programs
28/34
ENROLL: 110370111111 V.B.A EC-5TH/B
8. Place the following code in the cmdFind_Click event (disables navigating and updatingcontrols and enables "Find" controls):blnFirstFind = True
txtAuthor.Enabled = FalsetxtYearBorn.Enabled = FalsecmdMoveFirst.Enabled = FalsecmdMoveLast.Enabled = FalsecmdMovePrevious.Enabled = FalsecmdMoveNext.Enabled = FalsecmdDeleteRecord.Enabled = FalsecmdNewRecord.Enabled = FalsecmdUndo.Enabled = False
cmdSaveRecord.Enabled = FalsecmdCancelNew.Enabled = FalsecmdFind.Enabled = FalsecmdCancelFind.Enabled = TruecmdGo.Enabled = TruecboField.Enabled = TruecboRelOp.Enabled = TruetxtCriteria.Enabled = True9. Place the following code in the cmdGo_Click event (prepares criteria argument for the Find
methods, then performs the Find):Dim strQuote As StringDim strCriteria As StringIf cboField.Text = "Author" ThenstrQuote = "'"ElsestrQuote = ""txtCriteria = Val(txtCriteria)End IfstrCriteria = _cboField.Text & " " & cboRelOp.Text & _" " & strQuote & txtCriteria & strQuoteWith datAuthors.RecordsetIf blnFirstFind ThenblnFirstFind = False
NAME: Page 28
-
7/27/2019 Visual Basic Application Programs
29/34
ENROLL: 110370111111 V.B.A EC-5TH/B
.FindFirst strCriteriaElse.FindNext strCriteriaEnd IfIf .NoMatch Then
MsgBox "Data not found".Bookmark = strBookmarkcmdFind_ClickcmdFindAgain.Enabled = FalseElsecmdFindAgain.Enabled = TruecboField.Enabled = FalsecboRelOp.Enabled = FalsetxtCriteria.Enabled = False
cmdGo.Enabled = FalseEnd IfEnd With
10. In the cmdFindAgain_Click event, place the following line (performs the same actions as thecmdGo_Click event):cmdGo_Click
11. Place the following code in the cmdCancelFind_Click() event (enables the navigation andupdating controls, disables the Find controls):txtAuthor.Enabled = TruetxtYearBorn.Enabled = TruecmdMoveFirst.Enabled = TruecmdMoveLast.Enabled = TruecmdMovePrevious.Enabled = TruecmdMoveNext.Enabled = TruecmdDeleteRecord.Enabled = TruecmdNewRecord.Enabled = TruecmdUndo.Enabled = TruecmdSaveRecord.Enabled = TruecmdCancelNew.Enabled = TruecmdFind.Enabled = TruecmdCancelFind.Enabled = FalsecmdGo.Enabled = False
NAME: Page 29
-
7/27/2019 Visual Basic Application Programs
30/34
ENROLL: 110370111111 V.B.A EC-5TH/B
cboField.Enabled = FalsecboRelOp.Enabled = FalsetxtCriteria.Enabled = False12. Run the program and test the Find operations using different fields, relational operators, and
search strings.
NAME: Page 30
-
7/27/2019 Visual Basic Application Programs
31/34
ENROLL: 110370111111 V.B.A EC-5TH/B
EXERCISE 8
Using the MSFlexGrid ControlThe MSFlexGrid can be used to display multiple records in a grid. It cannot be used to edit dataor add and delete records. Follow the steps in this exercise to create a Categories and Products
master/detail form similar to the screen-shot shown below:
STEPS:1. Place two data controls on the form and set their properties as follows:
Name DatabaseName RecordSource Visible
datCategories ..\NWIND.MDB Categories TruedatProducts ..\NWIND.MDB (leave blank) FalseSet the Caption property of datCategories to "Use Arrow Buttons to Navigate Records".
NAME: Page 31
-
7/27/2019 Visual Basic Application Programs
32/34
ENROLL: 110370111111 V.B.A EC-5TH/B
2. Place three textboxes and one OLE control on the form. Set the DataSource property for eachof these four controls to datCategories.Set the DataField property for these controls to CategoryID, CategoryName, Description, andPicture respectively.
Set the Enabled property of the Category ID textbox to False. For the Description text box, set itsMultiLine property to True and set its ScrollBars property to 2 Vertical.Add appropriate label controls to accompany the textboxes, and group these four controls into aframe, as shown in the screen-shot.3. If necessary, add the MSFlexGrid to your toolbox from the Components item of the Projectmenu. Place an MSFlexGrid control on your form, and set its properties as follows:
Property ValueAllowUserResizing 1 flexResizeColumnsDataSource datProductsFixedCols 0
Enclose the grid in a frame, as shown in the screen-shot.
4. Place the following line of code in the Form_Load event:
datCategories.RefreshThis will force the controls bound to datCategories to be populated sooner than they wouldotherwise, and will also trigger the Reposition event of the datCategories control. (TheReposition event of a data control occurs whenever a Move method is executed against thatcontrol.)
5. Place the following code in the datCategories_Reposition event:
datProducts.RecordSource _= "SELECT * FROM Products " _& "WHERE CategoryID = " & txtCatIDdatProducts.Refresh6. Save and run the program.
NAME: Page 32
-
7/27/2019 Visual Basic Application Programs
33/34
ENROLL: 110370111111 V.B.A EC-5TH/B
EXERCISE 9
Using the DBGrid ControlThis exercise uses the DBGrid control, which goes a step further than the MSFlexGrid in thatallows the user to add, update, and delete records.
The DBGrid control does not install automatically when you install Visual Basic 6.0, but it isavailable on the VB 6/VS 6 CD. To install the DBGrid control, perform the following steps. Locate these three files on your VB6 installation CD: DBGRID32.OCX,DBGRID32.DEP, and DBGRID.REG. All three files should be located in this folder:D:\COMMON\TOOLS\VB\CONTROLS (where "D:" is the drive letter of your CD-ROMdrive). If you cannot locate your installation CD, you may download these three fileshere. 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 isWINNT\SYSTEM32; on XP the default is WINDOWS\SYSTEM32, and on 95, 98, and ME it isWINDOWS\SYSTEM). Double-click on DBGRID.REG to register the DBGRID32.OCX. You should now seethe control (under the name "Microsoft Data Bound Grid Control 5.0 (SP3)") when you accessthe Components dialog by selecting Project|Components within VB. (If not, click on theBrowse button in the Components dialog and locate the DBGRID32.OCX file bybrowsing to the folder in which you copied it previously.)
Once you have installed the DBGrid control, proceed with the steps of Exercise 9:
STEPS:
1. Copy your files from Exercise 8 to a new folder and open the project.2. Delete the MSFlexGrid control.3. Out of Project | Components, include the Microsoft Data Bound Grid Control.4. Place a DBGrid on your form in the position previously occupied by the flex grid.5. Set the DBGrid's properties as follows:
NAME: Page 33
http://www.vb6.us/files/VBPrograms/DBGridFiles.ziphttp://www.vb6.us/files/VBPrograms/DBGridFiles.ziphttp://www.vb6.us/files/VBPrograms/DBGridFiles.zip -
7/27/2019 Visual Basic Application Programs
34/34
ENROLL: 110370111111 V.B.A EC-5TH/B
Property ValueAllowAddNew TrueAllowDelete TrueAllowUpdate TrueDataSource datProducts
6. The code can remain as is. Save and run the program; experiment by using the gridto add, update, and delete records. While this application is certainly not bullet-proof, you'll findthat built-in error-checking will prevent most "illegal" actions attempted by the user (such astrying to change the primary key, changing a foreign key to a non-existent value, or deleting arecord with a related record in another table).