Sunday, March 2, 2014

How to Use ADODC in Visual Basic


1. Right click on the Visual Basic 6.0 program and choose 'Run as Administrator.' Start a new project by clicking on 'File' and then 'New Project.' Select the 'Data Project' template from the list.
2.
Double-click on the 'frmDataEnv' showing in the 'Data Project' list on the right. Place an ADO Data Control on the form by double-clicking on the ADODC control in the Toolbox on the left of the screen.
3.
Set up a connection to an existing database by right-clicking on the ADODC control now on the form and choosing 'ADODC Properties.' On the properties page, make sure the 'Use Connection String' option is selected and click 'Build.' Follow the steps that appear, which will lead you through selecting the type of data to use, where to find the database on your computer and whether or not to use a password.
4.
Click on the 'Test Connection' button on the 'Connection' tab of the Data Link Properties when all information from step 3 is complete. If the connection fails, go back and recheck the settings chosen to connect to your database.
5.
Place two Command buttons on the fmDataEnv by double-clicking on the 'Button' control in the Toolbox and then doing this again. Change the Name of one button to 'cmdAddNewRecord' and the Caption to 'Add New Record.' Change the Name of the other button to 'cmdDeleteRecord' and the Caption to 'Delete Record.'
6. Double-click on the 'cmdAddNewRecord' and insert this code between the beginning and end of the routine: 'Adodc1.Recordset.AddNew.' Do the same for the cmdDeleteRecord' button with this code: 'Adodc1.Recordset.Delete.' (Do not include the period at the end of this code.)
7. Write the code to take care of what should happen when the user clicks one of the choices in step 6:
Private Sub Form_Load()
Adodc1.Recordset.ActiveConnection.BeginTrans
End Sub
Private Sub Form_Unload(Cancel as Integer)
If MsgBox('Accept record changes?', vbYesNo) = vbYes Then
Adodc1.RecordSet.ActiveConnection.CommitTrans
Else
Adodc1.Recordsete.ActiveConnection.RollbackTrans
End If
End Sub
8.
Finish the ADODC setup by adding Labels and TextBox controls to the form to create a mechanism for a user to add or delete records. The specific controls will depend on the database needs. See the image for an example of how this will look.

No comments:

Post a Comment