Você está na página 1de 45

Visual Basic 6 (VB6)Visual Basic 6 (VB6) Syndicate content RSS: Site Feed Navigate To Home Tutorials Source Code

Samples Add Your Tutorial VB.NET Tutorials Forums Articles External Links Advertise Here! Contact Us Guides Beginner Guide Controls Guide Database Guide Introduction to SQL Using Data Control Using DAO Code Using RDO Using ADO ADO and ListView ADO stored procs Using Crystal Reports Navigation Create content User login Username: * Password: * Create new account Request new password Home Tutorials Database Access with the Data Control Level: Level2 Written By TheVBProgramer. 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 u sed in professional applications the norm is to write your own database access cod e so that you have complete control over the process. These exercises are worthw hile in that you can see what data bound controls are all about, but again be ad vised 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. T hese articles use the two sample Access databases provided with Visual Basic (BI BLIO.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:\Prog ram 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. T he DatabaseName property for the Data control in these exercises assumes that th e database file resides one directory level above the folder in which the exerci se 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 f orm 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 s et are DatabaseName 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 lab els. (If you were to open the database in Access, you would see that the three f ields 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.

When you want a control (such as a text box) to display data from a database, th e properties that must be set are DataSource and Datafield. The DataSource is th e name of the data control on the form (it should already be configured), and th e DataField is the name of the particular field in the database that should be d isplayed 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 throug h the data.

5. On any record, change the data in the author name or year born field. Move ah ead, 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 2 Using Navigation Buttons with a Data Control

In 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 ha ppening is that the data control is automatically invoking specific methods of t he recordset object: namely the MoveFirst, MovePrevious, MoveNext, and MoveLast methods. You can also invoke these methods through code, which is what this exer cise demonstrates.

STEPS:

1. Copy the files from Exercise #1 into a new folder and ope n the VBP file in the new folder. 2. Set the Visible property of the data control (datAuthors) to False.

3. 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, 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 cmdMoveNext_Click datAuthors.Recordset.MoveNext cmdMoveLast_Click datAuthors.Recordset.MoveLast cmdMovePrevious_Click

datAuthors.Recordset.MovePrevious cmdMoveFirst_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 happe ns? (We will fix this in Exercise 4.) EXERCISE 3 Using the BOFAction and EOFAction Properties of the Data Control

Note: EOF (End Of File) is a Boolean property of the recordset object that becom es true when an attempt is made to move forward past the last record in a record set.

BOF (Beginning Of File) is a Boolean property of the recordset object that becom es true when an attempt is made to move backward past the first record in a reco rdset.

STEPS:

1. Copy the files from Exercise #1 into a new folder and open the VBP file in th e new folder.

2. Click once on the data control and make sure that the fol lowing properties are set:

BOFAction = 0 EOFAction = 0

Move First Move Last

3. Run the program and notice what happens when you use the arrows to move previous w en 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 EOFAction = 1

BOF EOF

Notice what happens to the arrows on the data control when you try to move past the last or first record.

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; then click on the > arrow to move to the next record (which does n ot 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 th e 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 sti ll 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 datab ase table and to update rows in that table, but also allows the user to add a ne w record to that table without writing any code. EXERCISE 4 Using the EOF and BOF Properties with Navigation Buttons

STEPS:

1. Copy the files from Exercise #2 into a new folder and open the VBP file in th e new folder.

2. When the user clicks on the MoveNext button, and there is no next record, you r code should stay on the same record (the last one).

Put the following code in the cmdMoveNext_Click() event:

datAuthors.Recordset.MoveNext If datAuthors.Recordset.EOF = True Then datAuthors.Recordset.MoveLast End If

FYI: Instead of Recordset.MoveLast, you could use MoveFirst to let the user loop around to the first record.

3. Put similar code in the cmdMovePrevious_Click() event. In this case, you will be checking for Recordset.BOF = True.

4. Save and run the project and test it thoroughly.

EXERCISE 5 Adding, Updating and Deleting Records

In previous exercises, you saw that with the data control, changes to a record a re 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. You also saw that, by setting the EOFAction of the data control to "2 AddNew", the data control will invoke the AddNew method of the recordset object, which causes all the bound con trols to be cleared so that the user can enter data. In addition to being invoke d automatically through the data control, the Update and AddNew methods can also be invoked through code. The recordset object also has a Delete method, which c an only be invoked through code it cannot be accessed automatically through the da ta 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:

Name Caption Enabled cmdNewRecord New Record True cmdSaveRecord Save Record False cmdDeleteRecord Delete Record True

Your form should resemble the following:

3. When the user clicks on New Record, your program should e nable the Save Data button and disable the others. Put the following code in the cmdNewRecord_Click() event:

datAuthors.Recordset.AddNew cmdSaveRecord.Enabled = True cmdMoveFirst.Enabled = False cmdMoveLast.Enabled = False

cmdMovePrevious.Enabled = False cmdMoveNext.Enabled = False cmdDeleteRecord.Enabled = False cmdNewRecord.Enabled = False

4. Save and run the program to make sure the buttons are enabled and disabled co rrectly.

5. When the user clicks on the Save button to save the data that was entered, th e Update method should be called and the buttons should be redisplayed. Place th e following code in the cmdSaveRecord_Click() event:

datAuthors.Recordset.Update cmdSaveRecord.Enabled = False cmdMoveFirst.Enabled = True cmdMoveLast.Enabled = True cmdMovePrevious.Enabled = True cmdMoveNext.Enabled = True cmdDeleteRecord.Enabled = True cmdNewRecord.Enabled = True

6. Something to watch out for with the Delete method is that w hen 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 p revent this from happening, you should move the user to a valid record immediate ly following the delete.

Another issue is that if you attempt to delete a record that has a related recor d 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 c rash.

Finally, it is good programming practice to ask the user to confirm any destruct ive action.

Place the following code, which addresses the above-mentioned issues, in the cmd Delete_Click() event:

On Error GoTo Delete_Error

If MsgBox("Are you sure you want to delete this record?", _ vbQuestion + vbYesNo + vbDefaultButton2, _ "Confirm") = vbNo Then Exit Sub End If

'delete the current record datAuthors.Recordset.Delete 'move to a valid record cmdMoveNext_Click Exit Sub Delete_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 6 Using the Validate Event

This exercise will add the following functionality to the form you created in Ex ercise 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 ma

ke 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 La stModified properties of the recordset object, and the DataChanged property of b ound controls.

The Validate event of the data control occurs prior to a record Move and prior t o an Update, Delete, Unload, Close, or setting of a Bookmark. This means that an y code contained in the Validate event procedure will be executed prior to the e xecution of a statement containing one of these methods. For example, if somewhe re in your program you code the statement datAuthors.Recordset.Update, when VB e ncounters this statement, any code in the Validate event will be executed first.

The Validate event takes in two VB-provided arguments: Action and Save. (For exa mple, 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 comparin g it to a literal integer value (1, 2, 3, etc.) or with its corresponding VB pre defined constant (vbDataActionMoveFirst, vbDataActionUpdate, etc.). In addition, whatever action triggered the Validate event can be cancelled if you set the va lue of Action to zero (or to the predefined constant vbDataActionCancel) prior t o exiting the Validate event procedure. The values of Action and their correspon ding predefined constants are as follows:

Constant Value Description vbDataActionCancel 0 Cancel the operation when the Sub exits vbDataActionMoveFirst 1

MoveFirst method vbDataActionMovePrevious 2 MovePrevious method vbDataActionMoveNext 3 MoveNext method vbDataActionMoveLast 4 MoveLast method vbDataActionAddNew 5 AddNew method vbDataActionUpdate 6 Update operation (not UpdateRecord) vbDataActionDelete 7 Delete method vbDataActionFind 8 Find method

vbDataActionBookmark 9 The Bookmark property has been set vbDataActionClose 10 The Close method vbDataActionUnload 11 The form is being unloaded

The Save argument is a Boolean value indicating whether or not bound data has ch anged. You can 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 contro ls (such as the textboxes you have been using), typically used in the Validate e vent. 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 l ook something like the following: If txtMyField.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 or AddNew operation. For example, if a user invokes the Edit or AddNew meth od and hasn't yet invoked the Update method, CancelUpdate cancels any changes ma de after Edit or AddNew was invoked.

The UpdateControls method gets the current record from a Data control's Recordse t 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 cance l the changes. This method does not cause the Validate event to fire. Similarly, the UpdateRecord method (not used in this exercise) saves the current contents of bound controls to the database during the Validate event without triggering t he Validate event again.

Bookmark is a property of the Recordset object that contains a binary string ide ntifying 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 se tting the Bookmark property to that string variable.

LastModified is a property of the Recordset object that returns a bookmark indic ating 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 pr operties as follows:

Name Caption Enabled cmdUndo Undo True cmdCancelNew 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 Boolean Private blnValidationError As Boolean

4. Code the event procedure for the new cmdUndo button, which consists of only one statement:

datAuthors.UpdateControls

5. Modify the cmdNewRecord_Click() event procedure to look like the following (n ew statements are shown in bold):

datAuthors.Recordset.AddNew If blnValidationError Then Exit Sub

cmdSaveRecord.Enabled = True cmdCancelNew.Enabled = True

cmdMoveFirst.Enabled = False cmdMoveLast.Enabled = False cmdMovePrevious.Enabled = False cmdMoveNext.Enabled = False cmdDeleteRecord.Enabled = False cmdNewRecord.Enabled = False cmdUndo.Enabled = False

blnAddingNewRecord = True

Explanation When 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 blnVali dationError flag. This will catch the case where the user has modified the curre nt 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 th e problem with the current record. If everything's OK, we enable the "Cancel New" button so that they can cancel th e process, and disable the "Undo" button, because that is only applicable when t he user is changing, not adding a record. We also set the blnAddingNewRecord fla g to true, which will be tested in the Validate event (shown in a few steps belo w).

6. Modify the cmdSaveRecord_Click() event procedure to look like the following ( new statements are shown in bold):

datAuthors.Recordset.Update

If blnValidationError Then Exit Sub ' make the new record the current record datAuthors.Recordset.Bookmark _ = datAuthors.Recordset.LastModified

cmdSaveRecord.Enabled = False cmdCancelNew.Enabled = False

cmdMoveFirst.Enabled = True cmdMoveLast.Enabled = True cmdMovePrevious.Enabled = True cmdMoveNext.Enabled = True cmdDeleteRecord.Enabled = True cmdNewRecord.Enabled = True

cmdUndo.Enabled = True

blnAddingNewRecord = False

Explanation When the user initiates a save for a newly added record, the Update method is in voked (with the statement datAuthors.Recordset.Update). This will cause the Vali date event to fire, where we will set the blnValidationError flag. When the Vali date 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 co ntinue on our merry way.

The statement datAuthors.Recordset.Bookmark = datAuthors.Recordset.LastModified causes 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, becau se the AddNew method and subsequent Update method does not cause the newly added record to become the "current" record. Therefore, without this statement, the r ecord that was current before you invoked the "New Record" operation would be di splayed, and you would have to go to the last record to see the newly added reco rd.

Since this event completes the operation of adding a new record, the cmdCancelNe w button is disabled, the cmdUndo button is enabled and the blnAddingNewRecord f lag is set to False.

7. Code the Validate event procedure for the datAuthors data control. Recall tha t 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 c ontrol. The code is shown below:

Private Sub datAuthors_Validate(Action As Integer, 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.DataChanged Or blnAddingNewRecord Then If Trim$(txtAuthor) = "" Then

MsgBox "Author name must be entered" txtAuthor.SetFocus GoTo CancelValidateAction End If End If 'check to see if a valid year is entered If txtYearBorn.DataChanged Or blnAddingNewRecord Then If Val(txtYearBorn) = 0 Then MsgBox "Invalid year" txtYearBorn.SetFocus GoTo CancelValidateAction End If End If blnValidationError = False Exit Sub CancelValidateAction: blnValidationError = True Action = vbDataActionCancel Save = False

End Sub

8. Code the Click event procedure for the cmdCancelNew command button. If the us er 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 for m 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 AddNew datAuthors.Recordset.CancelUpdate datAuthors.UpdateControls

'enable & disable the appropriate buttons cmdSaveRecord.Enabled = False cmdCancelNew.Enabled = False cmdMoveFirst.Enabled = True cmdMoveLast.Enabled = True cmdMovePrevious.Enabled = True cmdMoveNext.Enabled = True cmdDeleteRecord.Enabled = True cmdNewRecord.Enabled = True cmdUndo.Enabled = True blnAddingNewRecord = False End Sub

9. Save, run and test the program. Make sure you understand what the code is doi ng.

EXERCISE 7 Using the Find Methods

The Recordset object has methods FindFirst, FindLast, FindNext, and FindPrevious . You can use these to search for a particular record in the Recordset.

The syntax is datControl.Recordset.FindFirst criteria where criteria is a string item consisting of a field name, a relational (compar ison) operator, and a value. It is essentially the same as a SQL WHERE clause wi thout the word WHERE. The comparison operators that can be used are =, >, <, >=, <=, <>, Like, Between, and In. The value on the right-hand side of the comparis on 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, that string must be enclosed i n double quotes. Typically, you must use VB's string-handling functions (especia

lly the "&" for concatenation) to get the desired results.

Examples: datBooks.Recordset.FindFirst "ISBN = '123-456-789-0' " datMembers.Recordset.FindNext "Amount > 100" datMembers.Recordset.FindNext "DateOfBirth < #1/1/1950#" datBooks.Recordset.FindNext "Amount > " & txtAmount.Text datMembers.Recordset.FindNext "FirstName = '" & txtName.Text & "'"

The next example assumes that the variable dtmBirthDay is of the Date data type:

datMembers.Recordset.FindNext _ "DateOfBirth < #" & Format$(dtmBirthDay, "mm/dd/yyyy") & "#"

In this exercise, the user selects both the field name and the relational operat or from combo boxes, then enters the search value in a textbox. The criteria for the Find methods are thus formed by statements similar to the following:

If cboField.Text = "Author" Then strQuote = "'" Else strQuote = "" txtCriteria.Text = Val(txtCriteria.Text) End If strCriteria = _ cboField.Text & " " & cboRelOp.Text & _ " " & strQuote & txtCriteria.Text & strQuote

datAuthors.Recordset.FindFirst strCriteria

Additional Notes:

If the name of the field in the database table has spaces in its name, yo u must put square 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 wil l contain an apostrophe, an extra measure should be taken to "double" the apostr ophes in the string otherwise, the apostrophe embedded in the string will be inter preted as the end of the string and a syntax error will most likely result. The easiest way to provide this "insurance" against embedded apostrophes is to use t he Replace$ function on the string in question to replace any occurrences of a s ingle apostrophe with two apostrophes:

datProducts.Recordset.FindFirst _ "ProductName = '" & Replace$(strSearchText, "'", "''") & "'"

For example, if strSearchText contained "Chef Anton's Cajun Gumbo", 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 SQ L parser as a single apostrophe.

In this particular example, if the Replace function was NOT used (i.e., you simp ly coded "ProductName = '" & strSearchText & "'" for the criteria, the result would be ProductName = 'Chef Anton's Cajun Gumbo' which would result in an error: the SQL parser would interpret the criteria to b e "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 u se a Find method and a record is not found, then the NoMatch property is set to True. You should use this property to determine whether or not a record was foun d. If a match is found, NoMatch will be set to True, and the found record become s the current record.

STEPS: 1. Copy the files from Exercise 6 into a new folder. Follow st

eps 2 through 4 to get your 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 True cmdFindAgain Find &Again False cmdCancelFind Cance&l Find False cmdGo &Go! False

3. Add two combo boxes and set their properties as follows (Note: you can set th e List property of a listbox or combo box in the Properties box by typing in val ues and pressing Ctrl+Enter - this action is analogous to using the AddItem meth od in code).

Name

Style Enabled List cboField 2 - Dropdown List False Au_Id Author [Year Born] cboRelOp 2 - Dropdown List False = > < >= <= <> Like

4. Add a textbox called txtCriteria and set its Enabled property to False.

5. Place the following statements in the Form_Load event:

cboField.Text = cboField.List(0)

cboRelOp.Text = cboRelOp.List(0)

6. Code the Click events for the combo boxes (to provide smoother navigation for the user). The Enabled tests are necessary because the Form_Load event assigns the first element of the their respective List property arrays to their respecti ve text properties, which automatically invokes the Click event, which will norm ally perform a SetFocus. SetFocus cannot be invoked on a disabled control; nor c an it be invoked prior to completion of a Form Load.

Private Sub cboField_Click() If cboField.Enabled Then cboRelOp.SetFocus End If End Sub

Private Sub cboRelOp_Click() If cboRelOp.Enabled Then txtCriteria.SetFocus End If End Sub

7. To ensure that strBookmark always references the current record, place this s tatement

strBookmark = datAuthors.Recordset.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 i n case the Find method fails, which leaves the current record pointer undefined.

8. Place the following code in the cmdFind_Click event (disables navigating and up dating controls and enables "Find" controls):

blnFirstFind = True txtAuthor.Enabled = False txtYearBorn.Enabled = False cmdMoveFirst.Enabled = False cmdMoveLast.Enabled = False cmdMovePrevious.Enabled = False cmdMoveNext.Enabled = False cmdDeleteRecord.Enabled = False cmdNewRecord.Enabled = False cmdUndo.Enabled = False cmdSaveRecord.Enabled = False cmdCancelNew.Enabled = False cmdFind.Enabled = False cmdCancelFind.Enabled = True cmdGo.Enabled = True cboField.Enabled = True cboRelOp.Enabled = True txtCriteria.Enabled = True

9. Place the following code in the cmdGo_Click event (prepares criteria argument for the Find methods, then performs the Find):

Dim strQuote As String Dim strCriteria As String If cboField.Text = "Author" Then strQuote = "'" Else

strQuote = "" txtCriteria = Val(txtCriteria) End If strCriteria = _ cboField.Text & " " & cboRelOp.Text & _ " " & strQuote & txtCriteria & strQuote

With datAuthors.Recordset If blnFirstFind Then blnFirstFind = False .FindFirst strCriteria Else .FindNext strCriteria End If If .NoMatch Then MsgBox "Data not found" .Bookmark = strBookmark cmdFind_Click cmdFindAgain.Enabled = False Else cmdFindAgain.Enabled = True cboField.Enabled = False cboRelOp.Enabled = False txtCriteria.Enabled = False cmdGo.Enabled = False End If End With

10. In the cmdFindAgain_Click event, place the following line (performs the same

actions as the cmdGo_Click event):

cmdGo_Click

11. Place the following code in the cmdCancelFind_Click() event (enables the nav igation and updating controls, disables the Find controls):

txtAuthor.Enabled = True txtYearBorn.Enabled = True cmdMoveFirst.Enabled = True cmdMoveLast.Enabled = True cmdMovePrevious.Enabled = True cmdMoveNext.Enabled = True cmdDeleteRecord.Enabled = True cmdNewRecord.Enabled = True cmdUndo.Enabled = True cmdSaveRecord.Enabled = True cmdCancelNew.Enabled = True cmdFind.Enabled = True cmdCancelFind.Enabled = False cmdGo.Enabled = False cboField.Enabled = False cboRelOp.Enabled = False txtCriteria.Enabled = False

12. Run the program and test the Find operations using different fields, relatio nal operators, and search strings.

EXERCISE 8 Using the MSFlexGrid Control

The MSFlexGrid can be used to display multiple records in a grid. It cannot be u

sed to edit data or 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 True datProducts ..\NWIND.MDB (leave blank) False

Set the Caption property of datCategories to "Use Arrow Buttons to Navigate Reco rds".

2. Place three textboxes and one OLE control on the form. Set the DataSource pro perty for each of these four controls to datCategories.

Set the DataField property for these controls to CategoryID, CategoryName, Descr iption, and Picture respectively.

Set the Enabled property of the Category ID textbox to False. For the Descriptio n text box, set its MultiLine property to True and set its ScrollBars property t o 2 Vertical.

Add appropriate label controls to accompany the textboxes, and group these four controls into a frame, as shown in the screen-shot.

3. If necessary, add the MSFlexGrid to your toolbox from the Components item of the Project menu. Place an MSFlexGrid control on your form, and set its properti es as follows:

Property Value AllowUserResizing 1 flexResizeColumns

DataSource datProducts FixedCols 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.Refresh

This will force the controls bound to datCategories to be populated sooner than they would otherwise, and will also trigger the Reposition event of the datCateg ories control. (The Reposition event of a data control occurs whenever a Move me thod is executed against that control.)

5. ent:

Place the following code in the datCategories_Reposition ev

datProducts.RecordSource _ = "SELECT * FROM Products " _ & "WHERE CategoryID = " & txtCatID datProducts.Refresh

6. Save and run the program. EXERCISE 9 Using the DBGrid Control

This exercise uses the DBGrid control, which goes a step further than the MSFlex Grid in that allows the user to add, update, and delete records.

The DBGrid control does not install automatically when you install Visual Basic 6.0, but it is available on the VB 6/VS 6 CD. To install the DBGrid control, per form the following steps.

Locate these three files on your VB6 installation CD: DBGRID32.OCX, DBGRI D32.DEP, and DBGRID.REG. All three files should be located in this folder: D:\CO MMON\TOOLS\VB\CONTROLS (where "D:" is the drive letter of your CD-ROM drive). If you cannot locate your installation CD, you may download these three files here . Copy these three files to your Windows "System" directory (the default sy stem directory varies depending on the OS being used: On Windows 2000 and NT the default is WINNT\SYSTEM32; on XP the default is WINDOWS\SYSTEM32, and on 95, 98 , and ME it is WINDOWS\SYSTEM). Double-click on DBGRID.REG to register the DBGRID32.OCX. You should now s ee the control (under the name "Microsoft Data Bound Grid Control 5.0 (SP3)") wh en you access the Components dialog by selecting Project Components within VB. (

If not, click on the Browse button in the Components dialog and locate the DBGRID3 ile by browsing 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. e project. 2.

Copy your files from Exercise 8 to a new folder and open th Delete the MSFlexGrid control.

3. nd Grid Control.

Out of Project

Components, include the Microsoft Data Bou

4. Place a DBGrid on your form in the position previously occu pied by the flex grid.

5.

Set the DBGrid's properties as follows:

Property Value AllowAddNew True AllowDelete True AllowUpdate True DataSource datProducts

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

Download the project files for these exercises here. Similar links Database Access with RDO (Remote Data Objects) Using ADO and the ListView control VB6 Animated Charts (With FusionCharts) VB6 Downloads Common Dialogs Allow A professional VB app Using Toolbars in Visual Basic Tutorial Working with Menus in VB6 Creating your own Drag and Drop apps in VB6 Using The VB6 Scroll Bars Control Tutorial Using VB6 File System Controls 376930 reads Mon, 10/10/2011 - 05:15 adodc1 pepito (not verified)

hi..thanks for a great tutorial.. hope you can help me with my problem... i made a system in which you can add,edit,save,delete anf find a record form ms access 2003 evrything works fine except for one.. its when i add a record and try to find it using my search box..but at the momen t i start to search..the newly created record will be deleted... where do you think my problem was??is it on the search or the adding one??? thanks..=) reply Fri, 09/23/2011 - 06:50 she (not verified) hi guys..i need your help!!im hi guys..i need your help!!im working on my dtabase project.i just wanted to kno w the easier code on how to edit and delete record in the visual basic using mic rosoft access version 7.0... its a big thing to me...i need your A.S.A.P (as soo n as possible) response.thanks reply Sun, 09/18/2011 - 08:40 aftab alam (not verified)

I have learned a lot from I have learned a lot from your site. thanks. reply Wed, 09/14/2011 - 00:13 Updating Record chetan (not verified)

Hello Sir/Madam, I m working on a project in VB and MS-Access as back end, and i am having proble ms while updating record in database, when i performs update operation it update s only 1st record in database, please let me know how to solve this as soon as p ossible. contact me on my email id - chetan.chetanmagar.magar@gmail.com . reply Tue, 08/23/2011 - 03:18 Rajeev12 (not verified) connectivity of vb6.0 with access2007 Hello, i want to connect an application design in vb6.0 with ms access2007, but still i could not connect. so, plz guide me. Thanks reply Wed, 09/14/2011 - 00:17 Sir, Visual Basic 6.0 chetan (not verified)

Sir, Visual Basic 6.0 is not compatible with MS-Access 2007, u should go with MS-Acce ss 2003, it supports Visual Basic 6.0. reply Mon, 08/22/2011 - 05:52 Search Ogola Odondo (not verified)

Hi, Am workin on my project but i av a problem. I need a code to search an item by u se of its id and display the results on a form in their corresponding controls l ike textboxes. I use Adodc control. Thanks. reply Tue, 07/05/2011 - 08:09 error Anonymous (not verified)

while cliking on resource type to enter data vb6 shows unregonised database form at error.... im using access 2007... pls.. help me reply

Thu, 06/23/2011 - 21:19 sri (not verified) i need form design & codings about medical store management i need form design & particulars reply Wed, 05/18/2011 - 02:26 vb connect ro ms access Anonymous (not verified)

i am not proper work to connect vb to ms access plz suggest me i m what do work in ms access and therefor vb work in detail with steps plz. reply Fri, 05/13/2011 - 03:18 Tharidu (not verified) problem in cmdGo_Click() plzzzzzz...... help There is a problem in cmdGo_Click() Run-time error '3251' : operation is not supported for this type of object. .FindFirst strCriteria .FindNext strCriteria reply Wed, 05/04/2011 - 11:18 i want code for saving Anonymous (not verified)

i want code for saving mulitiple entry bt there have to be increament of ID numb er per entry and have to check the records for duplicate ID. and it is have to b e for ADODC........... like adodc1.recordset.addnew etc.etc.etc.............. reply Mon, 05/02/2011 - 10:25 Anonymous (not verified) hi plzzzzzzzzzzzzzzzzzzzzzzzz. help me i am doing project by using vb in that i am facing problem in reading mill sec c hange in data that means in hav to monitor a one particular bit the changes from high to low v v fastly plz guide me in reading its argent...........plz maile me sindhu.hegde11@gmail.com reply Fri, 04/29/2011 - 00:07 login form santosh mishra

how to attach login form of vb6 to access database pls as soon as suggest me reply Tue, 07/05/2011 - 08:14 Anonymous (not verified) add data control of form den

add data control of form den on data control property set database name den set resource type den add mxhfield on form n set data sourcew to data 1 n den run it .......... make database table on access.... if u r using access 2007 version den save database format as 2002-2003... reply Thu, 04/14/2011 - 23:06 learning goood reply Sun, 03/27/2011 - 05:14 VB Great Job. . .thnx ! reply Fri, 03/18/2011 - 07:45 It's really sad Anonymous (not verified) Nabil (not verified) Anonymous (not verified)

It's really sad to see all these questions without answers. It's like car withou t wheels. reply Tue, 03/15/2011 - 05:23 save database to file aminsoraya (not verified)

hello that's realy nice and usefull i want to save project with code but i dont know that source code to save database if no hassle please sent me who can i use of source code or madule ! reply Tue, 03/15/2011 - 04:53 Girish Mahajan (not verified) Connect two database files and access records The above tutorial is very helpful and good. Thank You Please tell me how to connect two database in Access and and access the records from one database to another database And how to access the records using combo box reply Fri, 03/04/2011 - 08:36 Anonymous (not verified) runtime error 13 type mismatch hi everyone i got error on the my project on Go command plz help me & provide the solution.

this the my coding who i use it. on ( ) bracket field i got the error see in the last. Dim strQuote As String Dim strCriteria As String If cboField.Text = "ID" Then strQuote = "'" Else strQuote = "" txtCriteria.Text = Val(txtCriteria.Text) End If strCriteria = _ cboField.Text & " " & cboRelOp.Text & _ " " & strQuote & Replace$(txtCriteria.Text, "'", "''") & strQuote With datAuthors.Recordset If blnFirstFind Then blnFirstFind = False .FindFirst strCriteria Else (.FindNext strCriteria) End If If .NoMatch Then MsgBox "Data not found" (.Bookmark = strBookmark) cmdFind_Click cmdFindAgain.Enabled = False Else cmdFindAgain.Enabled = True cboField.Enabled = False cboRelOp.Enabled = False txtCriteria.Enabled = False cmdGo.Enabled = False End If End With End Sub reply Sat, 06/11/2011 - 13:12 You have to define the Anonymous (not verified)

You have to define the bookmark variable as type variant. Dim xxxx as variant reply Tue, 12/28/2010 - 03:27 tokata (not verified) understanding the database dear all, can you help me with connecting the vb6 to an access what should i do to create the access database may be it should be arranged from the access and the work with the data control in vb6 ???

thank you dear reply Mon, 02/14/2011 - 03:47 anver aslam (not verified) database connection with jet please be good enough to send me some sample program connection with ms access a nd visualbasic 6 with add delete, update,search with step by step as I am very k een to make simple program in vb reply Mon, 12/06/2010 - 03:06 vb 6.0 rahul singh (not verified)

how to search any record in vb 6.0 in data base.... data delte in 6.0 update in vb 6.0 please reply in my email id: singhprojects@yahoo.in reply Wed, 08/03/2011 - 20:07 obob idnih om mala nay? Anonymous (not verified)

obob idnih om mala nay? agnat!! reply Sat, 11/20/2010 - 04:02 Anonymous (not verified) i want to take microsoft i want to take microsoft data bound grid control 5.0 (sp3) in my component... but it not there....where i can download it????plizzz reply Sat, 10/23/2010 - 00:51 prateek (not verified) How to edit access database in vb 6.0 How to edit access database in vb 6.0 pls send me solution in vb code. reply Wed, 02/09/2011 - 18:47 re data1.recordset.edit reply Fri, 10/22/2010 - 21:24 Error Handler Anonymous (not verified) Anonymous (not verified)

Please help me. i have a project but i have a problem in adding record in databa se.Because 80004005 error is shown plz help me to resolve this problem.i m given you my code....

Private Sub Command1_Click() On Error GoTo ErrorHandler Error 424 'This error is displayed when there is a missing object Exit Sub ErrorHandler: MsgBox "Please Choose Another ID ", vbCritical, " ID Already Exist " If Text1.Text = "" Or Text2.Text = "" Or Combo1.Text = "" Or Text3.Text = "" The n MsgBox (" Complete The Form ") Else Set main.rs = main.cn.Execute("insert into employees (id,employeename,fathername ,contractorname)values ('" & Text3.Text & "'" & "," & "'" & Text1.Text & "'" & " ," & "'" & Text2.Text & "'" & "," & "'" & Combo1.Text & "'" & ") ") Text1.Text = "" Text2.Text = "" Text3.Text = "" Combo1.Text = "" End If reply Fri, 10/08/2010 - 23:27 Anonymous (not verified) can u pls tell me how can i edit a student detail records???? waiting your reply reply Tue, 10/05/2010 - 20:46 need help Anonymous (not verified)

d codings are too gud tanx a lot. but i m having a problem. wenevr i click the n ew record button , since the author_ID is auto generated each time i click new r ecord the id keeps increasing even if i do not save the record and also when i s top and play it again it still generates from the previously last enetered numbe r. hence if my last reocrd is 200 after clickin 5 tyms n 5nly den savin a record my last record id becomes 205 whi le my second last becomes 200. cn u plss help me validate dis . reply Fri, 10/01/2010 - 03:05 code thakur.ravi92

i need querry for deleting one record frm database.i m using access... reply Wed, 02/09/2011 - 18:50 lesser_code_12 data1.recordset.delete reply Sun, 08/22/2010 - 03:07 Farhan (not verified) hello. i would like to ask Anonymous (not verified)

hello. i would like to ask for a code which will create, save and delete tables in Ms Access. But it should do so with the help of vb6. for e.g we create 3 butt ons and then if we press one then a new table should be formed in ms access. Tha nku reply Tue, 09/21/2010 - 01:50 cmdDelete = Anonymous (not verified)

cmdDelete = Data1.Recordset.Delete Data1.Recordset.MoveFirst cmdCreate = Data1.Recordset.Save cmdUpdate = Data1.Recordset.Update reply Sat, 08/14/2010 - 09:24 EXCELLENT vikku (not verified)

GREAT TUTORIAL!! IT HELPS ME A LOT.....THANKS reply Wed, 08/11/2010 - 12:11 jvdpeet (not verified) Problem with data bound grid in Visual Basic I have the following problem with Dbgrid32.ocx: everything is coded and setup as required, but when I run it I only get two empty rows and the columns with the names, but empty cells. Whe I try to enter data in the fields = cells nothing ha ppens, although the cursor is shown. I also can navigate with the arrow keys for m cell to cell, but cannot enter data. Has anyone a solution? reply Tue, 08/10/2010 - 00:15 Anonymous (not verified) hi i need to know that how hi i need to know that how can we insert records in datagrid in vb so that the new record is inserted whereever we want in the database and the rtecords below it a utomatically move one place down and the serial number changes. reply Mon, 07/26/2010 - 00:00 using SQL commands Puneet Kumar (not verified)

gfgTHIS TUTORIAL IS EXCELLENT BUT I WANT TO KNOW HOW WE CAN USE SQL QUERIES BY T HIS DATA CONTROL reply Wed, 05/26/2010 - 01:46 RAHUL MEHTA (not verified) connection between vb 6.0 and Ms-Access

respected sir/madam, my query is that i want to build a connection between Ms-Access 2000 and visual basic 6.0 by coding. can u kindly help me with it. i have two fields in whch the data has to be added in the database using the application window having two text boxes and one comm and button to add. please help me with the code as soon as possible.. i have to submit my project on friday .i.e. 28/5/10. please help me as soon as p ossible with the coding perfectly working. :'( thanks & regards. reply Tue, 04/27/2010 - 21:37 vb Anonymous (not verified)

How can I include DAO using a database created in access from ADD-IN as part of the codes and not do the linking from the property box of the DATA LINK. So that when d program is burn on CD it can recognise the database created. reply Tue, 04/27/2010 - 04:11 Problem balram (not verified)

i have some problem when we access the username & password in MS access database by using the Visual Basic 6.0 program & how to compare the username & password which is already store in MS access database . reply Mon, 04/12/2010 - 05:04 Data Control Help Dear Sir/Madam, I am making a project for RTO agent. Now if I wish to connect the database I hav e created in Access using Data Control. It shows me en error as this: Unrecognized Data Format 'path of my access file'. Now please help me how can I connect my this database using data control. Thanks in advance.... reply Tue, 09/20/2011 - 00:14 colonelmoja (not verified) make sure the version of make sure the version of msaccess is '2000 or '97 reply Fri, 04/16/2010 - 08:48 zulqer nain (not verified) hey dude u have to install Darshan (not verified)

hey dude u have to install Service Pack 6 for Visual Basic 6.0 u can download it from this link http://www.microsoft.com/downloads/details.aspx?familyid=9EF9BF70-DFE1-42A1-A4C8 -39718C7E381D&displaylang=en cick on download then try. hey i m also a beginner of vb with excelent talent ok bye take care hey can u help me i wants to know how can we search a field content or record content etc plz do i f u can thank u reply Sun, 04/04/2010 - 10:39 mai (not verified) creating querry using data control how can i creating querry using data control in the code reply Sun, 04/04/2010 - 00:51 msflixgrid senthil (not verified)

i am using vb6. i have a text box showing the total number of persons and a msflixgrid in a form . when i click the text box the msflixgrid must display the datas pertaining to th e textbox I clicked. can anybody help me? reply Mon, 03/01/2010 - 19:18 i want to know Anonymous (not verified)

hi guys!! can anybody help me, regarding on data reports and data invironment? reply Sun, 02/28/2010 - 03:03 WOW! Kalindu Izanka (not verified)

Thanx for ur help.it helped me a l0t. keep sharing ur knowlegde.thanx!!! reply Mon, 08/23/2010 - 23:15 NICE TUTORIAL Anonymous (not verified)

Thanx very much. This tutorial helped me in my project. reply Sun, 02/28/2010 - 02:57 Thanx! Da Champzda (not verified)

Wow itz so cool. thanx a lot man....!It really worked......... reply

Sun, 01/31/2010 - 23:34 how do query

alshawi (not verified)

how do query between two tables oracle in v.b.6 reply Fri, 01/15/2010 - 11:39 2010? Mike - Brisbane (not verified)

what about data control for Access 2010 database? reply Fri, 01/08/2010 - 21:00 vb Anonymous (not verified)

hhhow we can access a data base table from vb data control. i cab connect Biblo table with vb data cnrol but any other table cannot be conaccess.plz tell me how we can access other data base tables from vb data control reply Thu, 01/07/2010 - 23:15 visual basic nosheen (not verified)

plz solve my problem i want to access table from vb data control . i can access biblo tables but no any other table so plz tell me how we can acces s any other table with vb data control reply Tue, 12/15/2009 - 02:54 Anonymous (not verified) it helps me lot thnx.... it helps me lot thnx.... reply Mon, 11/30/2009 - 05:16 mkrkarthi (not verified) Good Tutorial, How to Real time search ? It is very good tutorial. I want to search a particular record in real time whil e entering text in a text box. For e.g. In a school bill program, To select a student, type first few character s of the student name, then the relevant students name should be listed. How to do it? reply Wed, 10/28/2009 - 19:55 Vegeance (not verified) will nice explanation and tutorial,The guide was helpful to us! nice men,this tutorial help us a programmer like me who use a vb6 a lot..thanks dudietz reply Wed, 10/14/2009 - 22:15 Anees (not verified)

Thanks Thanks for Giving find first method in a simple form http://www.aneesv.co.cc reply Thu, 09/17/2009 - 05:23 pradnya (not verified) how to connect vb and access03 with ODBC Actually i know all about vb n access connection with adodc but i have no idea a bout ODBC Connection So pls Help me Thanks in advance reply Tue, 09/15/2009 - 18:56 Anonymous (not verified) how can data control caption how can data control caption is equal to record number of data?? reply Wed, 08/05/2009 - 04:43 thanks it helps a lot.. arianne (not verified)

thanks it helps a lot.. continue to share knowledge.. reply Mon, 08/03/2009 - 09:08 search using user input Anonymous (not verified)

I did VB Six years ago and now Im trying to search the database using two keys ( BatchID and Entry Number) I have already connected to the data base and have dat acontrol on the form displaying (BatchID, EntryNumber and print status) so i wan t to display the print status on a textbox after searching for it using the BAtc hID and entry Number that compares to it reply Mon, 07/27/2009 - 02:49 employee Anonymous (not verified)

hi i have one question "read unlimited employees names and their salaries and find out the highest salary getting employees name.". reply Mon, 07/27/2009 - 02:39 peace (not verified) how to connect payroll stystem with ms access? hi, i want to create payroll system of employee so i have some problem for coding th us pls provide me that oppertunities thanks reply

Tue, 04/27/2010 - 21:35 VB .... reply

Anonymous (not verified)

Sun, 07/12/2009 - 23:16 Ronak (not verified) Access Database-Updating specific record Hello, I'm making Address Book in vb6.I want to update a specific record when user seec ts a specific contact through list box.For that first i'm displaying user select ed record's details.Now after editing when i click on update button it replaces any one entry. Means Database is not understanding that i've to update user sele cted record.Any help whith proper code idea. Plz contact me on my mail ronu008@yahoo.com. thanxxx reply Sun, 07/05/2009 - 00:16 Updatecontrols monu (not verified)

Excellent Tutorial.but plz help me to know about the working of updatecontrols p roperly i am not able to understand the working of updatecontrols method of data control.plzzzzzzzzzzzzzzzzz it is very urgent for me because this is the part of my project. reply Mon, 07/06/2009 - 18:45 Good Day.... Anonymous (not verified)

This tutorial was great it helped understand what my Professor was discussing. Thank You... Keep up the good work.... reply 1 2 next last Post new comment Your name: E-mail: The content of this field is kept private and will not be shown publicly. Homepage: Subject: Comment: * Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> Lines and paragraphs break automatically. More information about formatting options Unless otherwise noted, all content on this site and in the source samples is Co pyrighted 2011 by the owner of vb6.us. All rights reserved - Contact Information

Você também pode gostar