beginning vb 6 databases

Download Beginning VB 6 Databases

If you can't read please download the document

Upload: duonglien

Post on 08-Dec-2016

218 views

Category:

Documents


2 download

TRANSCRIPT

Contacts.mdbCallTypeIDCallDescription

ContactIDLastNameFirstNameMiddleInitialBirthdayHomeStreetHomeCityHomeStateHomeZipHomePhoneHomeFaxHomeEmailHomeCellPhone

ContactIDDateOfCallCallTypeIDNotesOnPhoneCallCallCounter

Readme.txtReadme - Beginning VB 6 Databases

Please add Biblio.mdb and Nwind.mdb to this folder, C:\BegDB

To see the applications in action please select the .vbp or .vbg as applicable.

Visitors.mdbFirstNameLastNameCookieIDPreviousVisitTotalVisits

Chapter9/Page425/EYE.ICO

Chapter9/Page425/frmDBAnalyzer.frmVERSION 5.00Object = "{F9043C88-F6F2-101A-A3C9-08002B2F49FB}#1.2#0"; "COMDLG32.OCX"Object = "{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}#2.0#0"; "MSCOMCTL.OCX"Begin VB.Form frmDBAnalyzer Caption = "Microsoft Access Database Analyzer" ClientHeight = 4500 ClientLeft = 60 ClientTop = 345 ClientWidth = 6690 Icon = "frmDBAnalyzer.frx":0000 LinkTopic = "Form1" ScaleHeight = 4500 ScaleWidth = 6690 StartUpPosition = 3 'Windows Default Begin VB.CommandButton cmdAnalyze Caption = "&Analyze Database" Height = 495 Left = 3960 TabIndex = 5 Top = 3840 Width = 1815 End Begin VB.CommandButton cmdLocate Caption = "&Select Database" Height = 495 Left = 840 TabIndex = 4 Top = 3840 Width = 1815 End Begin MSComDlg.CommonDialog CommonDialog1 Left = 3120 Top = 3720 _ExtentX = 847 _ExtentY = 847 _Version = 393216 End Begin MSComctlLib.ProgressBar ProgressBar1 Height = 255 Left = 120 TabIndex = 3 Top = 3240 Width = 6375 _ExtentX = 11245 _ExtentY = 450 _Version = 393216 Appearance = 1 End Begin MSComctlLib.TreeView dbTree Height = 2535 Left = 120 TabIndex = 1 Top = 360 Width = 6375 _ExtentX = 11245 _ExtentY = 4471 _Version = 393217 Style = 7 Appearance = 1 End Begin VB.Label Label2 Alignment = 2 'Center Caption = "Scanning Tables in Database" ForeColor = &H00FF0000& Height = 255 Left = 120 TabIndex = 2 Top = 3000 Width = 6375 End Begin VB.Label lblTitle Caption = "Label1" Height = 255 Left = 120 TabIndex = 0 Top = 120 Width = 6375 EndEndAttribute VB_Name = "frmDBAnalyzer"Attribute VB_GlobalNameSpace = FalseAttribute VB_Creatable = FalseAttribute VB_PredeclaredId = TrueAttribute VB_Exposed = FalseOption ExplicitDim dataBaseLocation As String

Private Sub cmdAnalyze_Click()Dim dbase As DatabaseDim tble As TableDefDim fld As FieldDim prp As PropertyDim propString As StringDim treeNode As NodeDim currentFieldNumber As IntegerDim currentFieldKey As StringDim currentPropertyNumber As IntegerDim currentPropertyKey As StringDim currentTableName As StringDim currentTableCount As Integer

Screen.MousePointer = vbHourglass

'-Don't permit the user to click when analyzing --cmdAnalyze.Enabled = FalsecmdLocate.Enabled = False

currentTableCount = 0currentPropertyNumber = 1currentFieldNumber = 1

'-Clear the TreeView control from any prior analysis --dbTree.Nodes.Clear

'-Reasonability test ---If (InStr(1, dataBaseLocation, ".MDB", 1) < 1) Then Screen.MousePointer = vbDefault MsgBox ("Please select an MDB file.") cmdAnalyze.Enabled = True cmdLocate.Enabled = True Exit SubEnd If

'-Set our reference variable to the selected database --Set dbase = OpenDatabase(dataBaseLocation)

'-Reset the progress bar --ProgressBar1.Value = 0ProgressBar1.Max = dbase.TableDefs.Count

'-- The Root Node: The Name of the database --Set treeNode = dbTree.Nodes.Add(, , "r", _ "Database: " & dataBaseLocation)

'-- The next heirarchical structure is tables --Set treeNode = dbTree.Nodes.Add("r", tvwChild, _ "tble", "Tables")

'-- First, retrieve each table in the database --For Each tble In dbase.TableDefs currentTableCount = currentTableCount + 1 ProgressBar1.Value = currentTableCount currentTableName = "" & tble.Name & "" Set treeNode = dbTree.Nodes.Add("tble", _ tvwChild, currentTableName, tble.Name) '-- Now place the header 'Properties' under the table entry currentPropertyKey = "" & "Property" & _ CStr(currentPropertyNumber) & "" currentPropertyNumber = currentPropertyNumber + 1 Set treeNode = dbTree.Nodes.Add(currentTableName, tvwChild, _ currentPropertyKey, "Properties") With tble For Each prp In tble.Properties propString = RetrieveProp(prp) Set treeNode = dbTree.Nodes.Add(currentPropertyKey, _ tvwChild, , propString) Next currentFieldKey = "" & "Field " & CStr(currentFieldNumber) _ & "" currentFieldNumber = currentFieldNumber + 1 Set treeNode = dbTree.Nodes.Add(currentTableName, _ tvwChild, currentFieldKey, "Fields") For Each fld In .Fields Set treeNode = dbTree.Nodes.Add(currentFieldKey, _ tvwChild, , fld.Name) Next End WithNext

ProgressBar1.Value = 0cmdAnalyze.Enabled = TruecmdLocate.Enabled = TrueScreen.MousePointer = vbDefault

End Sub

Private Sub cmdLocate_Click()On Error GoTo ErrHandler

With CommonDialog1

.CancelError = True ' Set flags .Flags = cdlOFNHideReadOnly ' Set filters .Filter = "MS Access Files (*.MDB)|*.MDB" ' Specify default filter .FilterIndex = 1 .DialogTitle = "Select table to analyze" ' Display the Open dialog box .ShowOpen 'Display name of selected file dataBaseLocation = .FileName

End With

lblTitle = "Table Selected: " & dataBaseLocationcmdAnalyze.Enabled = True

Exit Sub ErrHandler: 'User pressed the Cancel button dataBaseLocation = "" lblTitle = "Selection Canceled" Exit Sub

End Sub

Public Function RetrieveProp(myProperty As Property) As String

Dim tempProperty As Variant

Err = 0

On Error Resume NexttempProperty = myProperty.Value

If (Err = 0) Then RetrieveProp = myProperty.Name If Len(tempProperty) Then RetrieveProp = RetrieveProp & " - Value: " & tempProperty End IfElse RetrieveProp = myProperty.NameEnd If

End Function

Chapter9/Page425/frmDBAnalyzer.frx

Chapter9/Page425/prjDBAnalyzer.vbpType=ExeReference=*\G{00020430-0000-0000-C000-000000000046}#2.0#0#..\..\..\WINDOWS\SYSTEM\STDOLE2.TLB#OLE AutomationReference=*\G{00025E01-0000-0000-C000-000000000046}#4.0#0#..\..\..\PROGRAM FILES\COMMON FILES\MICROSOFT SHARED\DAO\DAO350.DLL#Microsoft DAO 3.51 Object LibraryObject={F9043C88-F6F2-101A-A3C9-08002B2F49FB}#1.2#0; COMDLG32.OCXObject={831FDD16-0C5C-11D2-A9FC-0000F8754DA1}#2.0#0; MSCOMCTL.OCXForm=frmDBAnalyzer.frmStartup="frmDBAnalyzer"Command32=""Name="prjDBAnalyzer"HelpContextID="0"CompatibleMode="0"MajorVer=1MinorVer=0RevisionVer=0AutoIncrementVer=0ServerSupportFiles=0VersionCompanyName="Wrox Press"CompilationType=0OptimizationType=0FavorPentiumPro(tm)=0CodeViewDebugInfo=0NoAliasing=0BoundsCheck=0OverflowCheck=0FlPointCheck=0FDIVCheck=0UnroundedFP=0StartMode=0Unattended=0Retained=0ThreadPerObject=0MaxNumberOfThreads=1

[MS Transaction Server]AutoRefresh=1

Chapter9/Page425/prjDBAnalyzer.vbwfrmDBAnalyzer = 22, 29, 852, 543, , 0, 0, 0, 0, C

Chapter9/Page418/frmCreateDB.frmVERSION 5.00Begin VB.Form frmCreateDB Caption = "Form1" ClientHeight = 3195 ClientLeft = 60 ClientTop = 345 ClientWidth = 4680 LinkTopic = "Form1" ScaleHeight = 3195 ScaleWidth = 4680 StartUpPosition = 3 'Windows Default Begin VB.CommandButton cmdCreateDB Caption = "Command1" Height = 495 Left = 1800 TabIndex = 0 Top = 1320 Width = 1215 EndEndAttribute VB_Name = "frmCreateDB"Attribute VB_GlobalNameSpace = FalseAttribute VB_Creatable = FalseAttribute VB_PredeclaredId = TrueAttribute VB_Exposed = FalseOption ExplicitDim db As DatabaseDim tblDef As TableDefDim fldDef As FieldDim indx As IndexDim dbName As String

Private Sub cmdCreateDB_Click()dbName = "C:\BegDB\CONTACTS.MDB"If (Len(Dir(dbName))) Then Kill dbNameEnd If

Set db = DBEngine.Workspaces(0).CreateDatabase(dbName, dbLangGeneral)

Call createContactTable

Call createNotesTable

Call createCallTypeTable

Call createRelationships

MsgBox ("Database successfully created.")

End Sub

Public Sub createContactTable()

'-- Create the Contact table here --Set tblDef = db.CreateTableDef("Contact")

'-Create the fields in the contact table --Set fldDef = tblDef.CreateField("ContactID", dbLong)fldDef.Attributes = dbAutoIncrFieldtblDef.Fields.Append fldDefSet fldDef = tblDef.CreateField("LastName", dbText, 20)tblDef.Fields.Append fldDefSet fldDef = tblDef.CreateField("FirstName", dbText, 15)tblDef.Fields.Append fldDefSet fldDef = tblDef.CreateField("MiddleInitial", dbText, 1)tblDef.Fields.Append fldDefSet fldDef = tblDef.CreateField("Birthday", dbDate)tblDef.Fields.Append fldDefSet fldDef = tblDef.CreateField("HomeStreet", dbText, 20)tblDef.Fields.Append fldDefSet fldDef = tblDef.CreateField("HomeCity", dbText, 12)tblDef.Fields.Append fldDefSet fldDef = tblDef.CreateField("HomeState", dbText, 2)tblDef.Fields.Append fldDefSet fldDef = tblDef.CreateField("HomeZip", dbText, 10)tblDef.Fields.Append fldDefSet fldDef = tblDef.CreateField("HomePhone", dbText, 15)tblDef.Fields.Append fldDefSet fldDef = tblDef.CreateField("HomeFax", dbText, 15)tblDef.Fields.Append fldDefSet fldDef = tblDef.CreateField("HomeEmail", dbText, 30)tblDef.Fields.Append fldDefSet fldDef = tblDef.CreateField("HomeCellPhone", dbText, 15)tblDef.Fields.Append fldDefdb.TableDefs.Append tblDef

'-- Add the Primary Key --Set indx = tblDef.CreateIndex("PrimaryKey")Set fldDef = indx.CreateField("ContactID")indx.Fields.Append fldDefindx.Primary = TruetblDef.Indexes.Append indx

End Sub

Public Sub createNotesTable()

'-- Create the Notes table here --Set tblDef = db.CreateTableDef("Notes")

'-Create the fields in the Notes table --Set fldDef = tblDef.CreateField("ContactID", dbLong)tblDef.Fields.Append fldDefSet fldDef = tblDef.CreateField("DateOfCall", dbDate)tblDef.Fields.Append fldDefSet fldDef = tblDef.CreateField("CallTypeID", dbLong)tblDef.Fields.Append fldDefSet fldDef = tblDef.CreateField("NotesOnPhoneCall", dbMemo)tblDef.Fields.Append fldDefSet fldDef = tblDef.CreateField("CallCounter", dbLong)fldDef.Attributes = dbAutoIncrFieldtblDef.Fields.Append fldDefdb.TableDefs.Append tblDef

End Sub

Public Sub createCallTypeTable()

'-- Create the CallType table here --Set tblDef = db.CreateTableDef("CallType")

'-Create the fields in the CallType table --Set fldDef = tblDef.CreateField("CallTypeID", dbLong)fldDef.Attributes = dbAutoIncrFieldtblDef.Fields.Append fldDefSet fldDef = tblDef.CreateField("CallDescription", dbText, 20)tblDef.Fields.Append fldDefdb.TableDefs.Append tblDef

'-- Add the Primary Key --Set indx = tblDef.CreateIndex("PrimaryKey")Set fldDef = indx.CreateField("CallTypeID")indx.Fields.Append fldDefindx.Primary = TruetblDef.Indexes.Append indx

End Sub

Public Sub createRelationships()

Dim makeRelation As RelationDim fld As Field

Set makeRelation = db.CreateRelation("MyRelationship")makeRelation.Table = "Contact"makeRelation.ForeignTable = "Notes"

Set fld = makeRelation.CreateField("ContactID")fld.ForeignName = "ContactID"makeRelation.Fields.Append fldmakeRelation.Attributes = dbRelationDeleteCascadedb.Relations.Append makeRelation

End Sub

Chapter9/Page418/prjCreateDB.vbpType=ExeReference=*\G{00020430-0000-0000-C000-000000000046}#2.0#0#..\..\..\WINDOWS\SYSTEM\STDOLE2.TLB#OLE AutomationReference=*\G{00025E01-0000-0000-C000-000000000046}#4.0#0#..\..\..\PROGRAM FILES\COMMON FILES\MICROSOFT SHARED\DAO\DAO350.DLL#Microsoft DAO 3.51 Object LibraryForm=frmCreateDB.frmStartup="frmCreateDB"Command32=""Name="prjCreateDB"HelpContextID="0"CompatibleMode="0"MajorVer=1MinorVer=0RevisionVer=0AutoIncrementVer=0ServerSupportFiles=0VersionCompanyName="Wrox Press"CompilationType=0OptimizationType=0FavorPentiumPro(tm)=0CodeViewDebugInfo=0NoAliasing=0BoundsCheck=0OverflowCheck=0FlPointCheck=0FDIVCheck=0UnroundedFP=0StartMode=0Unattended=0Retained=0ThreadPerObject=0MaxNumberOfThreads=1

[MS Transaction Server]AutoRefresh=1

Chapter9/Page418/prjCreateDB.vbwfrmCreateDB = 44, 58, 741, 679, , 22, 29, 719, 650, C

Chapter9/Page417/frmTables.frmVERSION 5.00Begin VB.Form frmTables Caption = "Form1" ClientHeight = 3330 ClientLeft = 60 ClientTop = 345 ClientWidth = 2640 LinkTopic = "Form1" ScaleHeight = 3330 ScaleWidth = 2640 StartUpPosition = 3 'Windows Default Begin VB.CommandButton Command1 Caption = "DAO Collection" Height = 495 Left = 480 TabIndex = 1 Top = 2400 Width = 1695 End Begin VB.ListBox List1 Height = 2010 Left = 240 TabIndex = 0 Top = 120 Width = 2175 EndEndAttribute VB_Name = "frmTables"Attribute VB_GlobalNameSpace = FalseAttribute VB_Creatable = FalseAttribute VB_PredeclaredId = TrueAttribute VB_Exposed = FalseOption Explicit

Private Sub Command1_Click()Dim myDatabase As DatabaseDim myTable As TableDef 'this will hold the tableDef(inition)Dim myFields As FieldsDim myField As Field

Set myDatabase = OpenDatabase("C:\BegDB\BIBLIO.MDB")

For Each myTable In myDatabase.TableDefs 'dots to get the tableDefs List1.AddItem myTable.Name & " has " & myTable.Fields.Count _ & " fields"Next

End Sub

Chapter9/Page417/prjTables.vbpType=ExeReference=*\G{00020430-0000-0000-C000-000000000046}#2.0#0#..\..\..\WINDOWS\SYSTEM\STDOLE2.TLB#OLE AutomationReference=*\G{00025E01-0000-0000-C000-000000000046}#4.0#0#..\..\..\PROGRAM FILES\COMMON FILES\MICROSOFT SHARED\DAO\DAO350.DLL#Microsoft DAO 3.51 Object LibraryForm=frmTables.frmStartup="frmTables"Command32=""Name="prjTables"HelpContextID="0"CompatibleMode="0"MajorVer=1MinorVer=0RevisionVer=0AutoIncrementVer=0ServerSupportFiles=0VersionCompanyName="Wrox Press"CompilationType=0OptimizationType=0FavorPentiumPro(tm)=0CodeViewDebugInfo=0NoAliasing=0BoundsCheck=0OverflowCheck=0FlPointCheck=0FDIVCheck=0UnroundedFP=0StartMode=0Unattended=0Retained=0ThreadPerObject=0MaxNumberOfThreads=1

[MS Transaction Server]AutoRefresh=1

Chapter9/Page417/prjTables.vbwfrmTables = 22, 29, 852, 519, , 0, 0, 0, 0, C

Chapter9/Page414/frmTables.frmVERSION 5.00Begin VB.Form frmTables Caption = "Form1" ClientHeight = 3330 ClientLeft = 60 ClientTop = 345 ClientWidth = 2640 LinkTopic = "Form1" ScaleHeight = 3330 ScaleWidth = 2640 StartUpPosition = 3 'Windows Default Begin VB.CommandButton Command1 Caption = "DAO Collection" Height = 495 Left = 480 TabIndex = 1 Top = 2400 Width = 1695 End Begin VB.ListBox List1 Height = 2010 Left = 240 TabIndex = 0 Top = 120 Width = 2175 EndEndAttribute VB_Name = "frmTables"Attribute VB_GlobalNameSpace = FalseAttribute VB_Creatable = FalseAttribute VB_PredeclaredId = TrueAttribute VB_Exposed = FalseOption Explicit

Private Sub Command1_Click()Dim myDatabase As DatabaseDim myTable As TableDef 'this will hold the tableDef(inition)

Set myDatabase = OpenDatabase("C:\BegDB\BIBLIO.MDB")

For Each myTable In myDatabase.TableDefs 'dots to get the tableDefs List1.AddItem myTable.Name 'dots to get the namesNext

End Sub

Chapter9/Page414/prjTables.vbpType=ExeReference=*\G{00020430-0000-0000-C000-000000000046}#2.0#0#..\..\..\WINDOWS\SYSTEM\STDOLE2.TLB#OLE AutomationReference=*\G{00025E01-0000-0000-C000-000000000046}#4.0#0#..\..\..\PROGRAM FILES\COMMON FILES\MICROSOFT SHARED\DAO\DAO350.DLL#Microsoft DAO 3.51 Object LibraryForm=frmTables.frmStartup="frmTables"Command32=""Name="prjTables"HelpContextID="0"CompatibleMode="0"MajorVer=1MinorVer=0RevisionVer=0AutoIncrementVer=0ServerSupportFiles=0VersionCompanyName="Wrox Press"CompilationType=0OptimizationType=0FavorPentiumPro(tm)=0CodeViewDebugInfo=0NoAliasing=0BoundsCheck=0OverflowCheck=0FlPointCheck=0FDIVCheck=0UnroundedFP=0StartMode=0Unattended=0Retained=0ThreadPerObject=0MaxNumberOfThreads=1

[MS Transaction Server]AutoRefresh=1

Chapter9/Page414/prjTables.vbwfrmTables = 22, 29, 852, 519, C, 0, 0, 0, 0, C

Chapter8/Page380/DSQL.vbpType=ExeForm=Form1.frmReference=*\G{00020430-0000-0000-C000-000000000046}#2.0#0#..\..\..\WINDOWS\SYSTEM\STDOLE2.TLB#OLE AutomationObject={00028C01-0000-0000-0000-000000000046}#1.0#0; DBGRID32.OCXReference=*\G{00025E01-0000-0000-C000-000000000046}#4.0#0#..\..\..\PROGRAM FILES\COMMON FILES\MICROSOFT SHARED\DAO\DAO350.DLL#Microsoft DAO 3.51 Object LibraryIconForm="Form1"Startup="Form1"Command32=""Name="DSQL"HelpContextID="0"CompatibleMode="0"MajorVer=1MinorVer=0RevisionVer=0AutoIncrementVer=0ServerSupportFiles=0VersionCompanyName="Wrox Press"CompilationType=0OptimizationType=0FavorPentiumPro(tm)=0CodeViewDebugInfo=0NoAliasing=0BoundsCheck=0OverflowCheck=0FlPointCheck=0FDIVCheck=0UnroundedFP=0StartMode=0Unattended=0Retained=0ThreadPerObject=0MaxNumberOfThreads=1

[MS Transaction Server]AutoRefresh=1

Chapter8/Page380/Form1.frmVERSION 5.00Object = "{00028C01-0000-0000-0000-000000000046}#1.0#0"; "DBGRID32.OCX"Begin VB.Form Form1 Caption = "Simple Dynamic SQL Statement" ClientHeight = 4140 ClientLeft = 60 ClientTop = 345 ClientWidth = 5595 LinkTopic = "Form1" ScaleHeight = 4140 ScaleWidth = 5595 StartUpPosition = 3 'Windows Default Begin MSDBGrid.DBGrid DBGrid1 Bindings = "Form1.frx":0000 Height = 2775 Left = 120 OleObjectBlob = "Form1.frx":0014 TabIndex = 0 Top = 120 Width = 5295 End Begin VB.Data Data2 Caption = "Data2" Connect = "Access" DatabaseName = "C:\BegDB\Biblio.mdb" DefaultCursorType= 0 'DefaultCursor DefaultType = 2 'UseODBC Exclusive = 0 'False Height = 420 Left = 3480 Options = 0 ReadOnly = 0 'False RecordsetType = 1 'Dynaset RecordSource = "" Top = 3600 Visible = 0 'False Width = 1980 End Begin VB.Data Data1 Caption = "Data1" Connect = "Access" DatabaseName = "C:\BegDB\Biblio.mdb" DefaultCursorType= 0 'DefaultCursor DefaultType = 2 'UseODBC Exclusive = 0 'False Height = 420 Left = 3480 Options = 0 ReadOnly = 0 'False RecordsetType = 1 'Dynaset RecordSource = "" Top = 3000 Visible = 0 'False Width = 1980 End Begin VB.ListBox List1 Height = 1035 Left = 120 TabIndex = 1 Top = 3000 Width = 3135 EndEndAttribute VB_Name = "Form1"Attribute VB_GlobalNameSpace = FalseAttribute VB_Creatable = FalseAttribute VB_PredeclaredId = TrueAttribute VB_Exposed = FalseOption Explicit

Private Sub Form_Load()Dim mySQL As String

mySQL = "SELECT City FROM Publishers GROUP BY City"

Data1.RecordSource = mySQLData1.Refresh

While Not Data1.Recordset.EOF 'loop through all of the records returned With Data1.Recordset If (Not IsNull(!city)) Then 'ensure that the field is not null List1.AddItem !city 'if the field is not null, add it End If .MoveNext End WithWend

End Sub

Private Sub List1_Click()

Data2.RecordSource = "SELECT * FROM Publishers WHERE City = '" & _ List1 & "' ORDER BY Name"Data2.Refresh

End Sub

Chapter8/Page380/Form1.frx

Chapter8/Page372/frmSQL.frmVERSION 5.00Object = "{00028C01-0000-0000-0000-000000000046}#1.0#0"; "DBGRID32.OCX"Begin VB.Form frmSQL Caption = "SQL Query Tester" ClientHeight = 4695 ClientLeft = 60 ClientTop = 345 ClientWidth = 6450 LinkTopic = "Form1" ScaleHeight = 4695 ScaleWidth = 6450 StartUpPosition = 3 'Windows Default Begin MSDBGrid.DBGrid DBGrid1 Bindings = "frmSQL.frx":0000 Height = 1815 Left = 120 OleObjectBlob = "frmSQL.frx":0014 TabIndex = 0 Top = 120 Width = 6135 End Begin VB.TextBox Text1 Height = 1575 Left = 120 MultiLine = -1 'True ScrollBars = 2 'Vertical TabIndex = 8 Top = 3000 Width = 4095 End Begin VB.CommandButton cmdRun Caption = "&Execute" Height = 495 Left = 4440 TabIndex = 7 Top = 3000 Width = 1815 End Begin VB.Data Data1 Caption = "Data1" Connect = "Access" DatabaseName = "C:\BegDB\Biblio.mdb" DefaultCursorType= 0 'DefaultCursor DefaultType = 2 'UseODBC Exclusive = 0 'False Height = 345 Left = 5280 Options = 0 ReadOnly = 0 'False RecordsetType = 1 'Dynaset RecordSource = "" Top = 4200 Width = 1140 End Begin VB.Label lblUpdatable BorderStyle = 1 'Fixed Single Height = 495 Left = 4440 TabIndex = 6 Top = 2400 Width = 1815 End Begin VB.Label lblCurrentRecord BorderStyle = 1 'Fixed Single Height = 495 Left = 2280 TabIndex = 5 Top = 2400 Width = 1815 End Begin VB.Label lblRecordCount BorderStyle = 1 'Fixed Single Height = 495 Left = 120 TabIndex = 4 Top = 2400 Width = 1815 End Begin VB.Label Label3 Caption = "Updatable" Height = 255 Left = 4440 TabIndex = 3 Top = 2040 Width = 1695 End Begin VB.Label Label2 Caption = "Current Record" Height = 255 Left = 2280 TabIndex = 2 Top = 2040 Width = 1575 End Begin VB.Label Label1 Caption = "Record Count" Height = 255 Left = 120 TabIndex = 1 Top = 2040 Width = 1695 EndEndAttribute VB_Name = "frmSQL"Attribute VB_GlobalNameSpace = FalseAttribute VB_Creatable = FalseAttribute VB_PredeclaredId = TrueAttribute VB_Exposed = FalseOption Explicit

Private Sub cmdRun_Click()On Error GoTo SQLError:

Data1.RecordSource = Text1Data1.Refresh

If Data1.RecordSource "" Then If (Data1.Recordset.RecordCount > 0) Then With Data1.Recordset .MoveLast .MoveFirst lblRecordCount = .RecordCount lblUpdatable = IIf(.Updatable, "Yes", "No") End With Else lblRecordCount = "Records Returned: 0" lblCurrentRecord = "No records" lblUpdatable = "" End IfElse MsgBox ("Please enter an SQL statement")End If

Exit SubSQLError: Dim sError As String sError = "Error Number: " & Err.Number & vbCrLf sError = sError & Err.Description MsgBox (sError) Exit Sub

End Sub

Private Sub Data1_Reposition()

lblCurrentRecord = Data1.Recordset.AbsolutePosition + 1

End Sub

Chapter8/Page372/frmSQL.frx

Chapter8/Page372/frmUpdate.frmVERSION 5.00Begin VB.Form frmUpdate Caption = "Modifying Biblio.mdb" ClientHeight = 2820 ClientLeft = 60 ClientTop = 345 ClientWidth = 3765 LinkTopic = "Form1" ScaleHeight = 2820 ScaleWidth = 3765 StartUpPosition = 3 'Windows Default Begin VB.Data Data1 Caption = "Data1" Connect = "Access" DatabaseName = "C:\BegDB\Biblio.mdb" DefaultCursorType= 0 'DefaultCursor DefaultType = 2 'UseODBC Exclusive = 0 'False Height = 420 Left = 840 Options = 0 ReadOnly = 0 'False RecordsetType = 1 'Dynaset RecordSource = "" Top = 2160 Width = 1740 End Begin VB.CommandButton cmdNewYork Caption = "&Update to New York" Height = 615 Left = 840 TabIndex = 1 Top = 1200 Width = 1695 End Begin VB.CommandButton cmdIpswitch Caption = "&Change to Ipswitch" Height = 615 Left = 840 TabIndex = 0 Top = 240 Width = 1695 EndEndAttribute VB_Name = "frmUpdate"Attribute VB_GlobalNameSpace = FalseAttribute VB_Creatable = FalseAttribute VB_PredeclaredId = TrueAttribute VB_Exposed = FalseOption Explicit

Private Sub cmdIpswitch_Click()With Data1 .RecordSource = "SELECT * FROM Publishers WHERE City = 'New York'" .Refresh .Recordset.MoveFirst While (Not .Recordset.EOF) .Recordset.Edit .Recordset!City = "Ipswitch" .Recordset.Update .Recordset.MoveNext WendEnd With

End Sub

Private Sub cmdNewYork_Click()Dim dbBiblio As Database

Set dbBiblio = OpenDatabase("C:\BegDB\Biblio.mdb")dbBiblio.Execute "UPDATE Publishers SET City = " & _ "'New York' WHERE City = 'Ipswitch'"End Sub

Chapter8/Page372/prjSQL.vbpType=ExeForm=frmSQL.frmReference=*\G{00020430-0000-0000-C000-000000000046}#2.0#0#..\..\..\WINDOWS\SYSTEM\STDOLE2.TLB#OLE AutomationObject={00028C01-0000-0000-0000-000000000046}#1.0#0; DBGRID32.OCXReference=*\G{00025E01-0000-0000-C000-000000000046}#4.0#0#..\..\..\PROGRAM FILES\COMMON FILES\MICROSOFT SHARED\DAO\DAO350.DLL#Microsoft DAO 3.51 Object LibraryForm=frmUpdate.frmIconForm="frmSQL"Startup="frmUpdate"HelpFile=""Command32=""Name="prjSQL"HelpContextID="0"CompatibleMode="0"MajorVer=1MinorVer=0RevisionVer=0AutoIncrementVer=0ServerSupportFiles=0VersionCompanyName="Wrox Press"CompilationType=0OptimizationType=0FavorPentiumPro(tm)=0CodeViewDebugInfo=0NoAliasing=0BoundsCheck=0OverflowCheck=0FlPointCheck=0FDIVCheck=0UnroundedFP=0StartMode=0Unattended=0Retained=0ThreadPerObject=0MaxNumberOfThreads=1

[MS Transaction Server]AutoRefresh=1

Chapter8/Page347/frmSQL.frmVERSION 5.00Object = "{00028C01-0000-0000-0000-000000000046}#1.0#0"; "DBGRID32.OCX"Begin VB.Form frmSQL Caption = "SQL Query Tester" ClientHeight = 4695 ClientLeft = 60 ClientTop = 345 ClientWidth = 6450 LinkTopic = "Form1" ScaleHeight = 4695 ScaleWidth = 6450 StartUpPosition = 3 'Windows Default Begin MSDBGrid.DBGrid DBGrid1 Bindings = "frmSQL.frx":0000 Height = 1815 Left = 120 OleObjectBlob = "frmSQL.frx":0014 TabIndex = 0 Top = 120 Width = 6135 End Begin VB.TextBox Text1 Height = 1575 Left = 120 MultiLine = -1 'True ScrollBars = 2 'Vertical TabIndex = 8 Top = 3000 Width = 4095 End Begin VB.CommandButton cmdRun Caption = "&Execute" Height = 495 Left = 4440 TabIndex = 7 Top = 3000 Width = 1815 End Begin VB.Data Data1 Caption = "Data1" Connect = "Access" DatabaseName = "C:\BegDB\Biblio.mdb" DefaultCursorType= 0 'DefaultCursor DefaultType = 2 'UseODBC Exclusive = 0 'False Height = 345 Left = 5280 Options = 0 ReadOnly = 0 'False RecordsetType = 1 'Dynaset RecordSource = "" Top = 4200 Width = 1140 End Begin VB.Label lblUpdatable BorderStyle = 1 'Fixed Single Height = 495 Left = 4440 TabIndex = 6 Top = 2400 Width = 1815 End Begin VB.Label lblCurrentRecord BorderStyle = 1 'Fixed Single Height = 495 Left = 2280 TabIndex = 5 Top = 2400 Width = 1815 End Begin VB.Label lblRecordCount BorderStyle = 1 'Fixed Single Height = 495 Left = 120 TabIndex = 4 Top = 2400 Width = 1815 End Begin VB.Label Label3 Caption = "Updatable" Height = 255 Left = 4440 TabIndex = 3 Top = 2040 Width = 1695 End Begin VB.Label Label2 Caption = "Current Record" Height = 255 Left = 2280 TabIndex = 2 Top = 2040 Width = 1575 End Begin VB.Label Label1 Caption = "Record Count" Height = 255 Left = 120 TabIndex = 1 Top = 2040 Width = 1695 EndEndAttribute VB_Name = "frmSQL"Attribute VB_GlobalNameSpace = FalseAttribute VB_Creatable = FalseAttribute VB_PredeclaredId = TrueAttribute VB_Exposed = FalseOption Explicit

Private Sub cmdRun_Click()On Error GoTo SQLError:

Data1.RecordSource = Text1Data1.Refresh

If Data1.RecordSource "" Then If (Data1.Recordset.RecordCount > 0) Then With Data1.Recordset .MoveLast .MoveFirst lblRecordCount = .RecordCount lblUpdatable = IIf(.Updatable, "Yes", "No") End With Else lblRecordCount = "Records Returned: 0" lblCurrentRecord = "No records" lblUpdatable = "" End IfElse MsgBox ("Please enter an SQL statement")End If

Exit SubSQLError: Dim sError As String sError = "Error Number: " & Err.Number & vbCrLf sError = sError & Err.Description MsgBox (sError) Exit Sub

End Sub

Private Sub Data1_Reposition()

lblCurrentRecord = Data1.Recordset.AbsolutePosition + 1

End Sub

Chapter8/Page347/frmSQL.frx

Chapter8/Page347/prjSQL.vbpType=ExeForm=frmSQL.frmReference=*\G{00020430-0000-0000-C000-000000000046}#2.0#0#..\..\..\WINDOWS\SYSTEM\STDOLE2.TLB#OLE AutomationObject={00028C01-0000-0000-0000-000000000046}#1.0#0; DBGRID32.OCXReference=*\G{00025E01-0000-0000-C000-000000000046}#4.0#0#..\..\..\PROGRAM FILES\COMMON FILES\MICROSOFT SHARED\DAO\DAO350.DLL#Microsoft DAO 3.51 Object LibraryIconForm="frmSQL"Startup="frmSQL"Command32=""Name="prjSQL"HelpContextID="0"CompatibleMode="0"MajorVer=1MinorVer=0RevisionVer=0AutoIncrementVer=0ServerSupportFiles=0VersionCompanyName="Wrox Press"CompilationType=0OptimizationType=0FavorPentiumPro(tm)=0CodeViewDebugInfo=0NoAliasing=0BoundsCheck=0OverflowCheck=0FlPointCheck=0FDIVCheck=0UnroundedFP=0StartMode=0Unattended=0Retained=0ThreadPerObject=0MaxNumberOfThreads=1

[MS Transaction Server]AutoRefresh=1

Chapter7/Page330/dataClass.clsVERSION 1.0 CLASSBEGIN MultiUse = -1 'True Persistable = 0 'NotPersistable DataBindingBehavior = 0 'vbNone DataSourceBehavior = 0 'vbNone MTSTransactionMode = 0 'NotAnMTSObjectENDAttribute VB_Name = "dataClass"Attribute VB_GlobalNameSpace = FalseAttribute VB_Creatable = TrueAttribute VB_PredeclaredId = FalseAttribute VB_Exposed = FalseAttribute VB_Description = "This class is used to manage the functionality of a data control. It can instantiated in a form and will then handle an associated data control."Attribute VB_Ext_KEY = "SavedWithClassBuilder6" ,"Yes"Attribute VB_Ext_KEY = "Top_Level" ,"Yes"Option Explicit

'local variable(s) to hold property value(s)Private mvardataCtl As Object 'local copyPrivate mvarButtons As String 'local copyPrivate mvardbName As String 'local copyPrivate mvarFormName As Object 'local copyPrivate mvarLabelToUpdate As String 'local copyPrivate mvarProgressBar As Object 'local copyPrivate mvarRecordSource As String 'local copyPrivate mvarTag As String 'local copyPrivate mvarTotalRecords As Long

Private Enum cmdButtons cmdMoveFirst = 0 cmdMovePrevious = 1 cmdMoveNext = 2 cmdMoveLast = 3 cmdAddNew = 4 cmdEdit = 5 cmdSave = 6 cmdDelete = 7 cmdUndo = 8 cmdFind = 9 cmdDone = 10End Enum

'local variable(s) to hold property value(s)Private mvarFindCaption As String 'local copyPrivate mvarFindRecordSource As String 'local copyPrivate mvarFindMatchField As String 'local copy

Private Function BuildCriteria() As String

Dim sCriteria As String Dim fField As Field Dim sMessage As String Dim iIndx As Integer Set fField = mvardataCtl.Recordset.Fields(mvarFindMatchField) Select Case fField.Type Case dbInteger, dbLong, dbCurrency, dbSingle, dbDouble BuildCriteria = "" & mvarFindMatchField & " = " & gFindString Case dbDate BuildCriteria = "" & mvarFindMatchField & " = #" & gFindString & "#" Case dbText BuildCriteria = "" & mvarFindMatchField & " = '" & gFindString & "'" Case Else sMessage = "Sorry, you can't use the find feature on fields" sMessage = sMessage & " of type: " & fField.Type iIndx = MsgBox(sMessage, vbCritical, App.EXEName)End SelectEnd Function

Public Property Let FindMatchField(ByVal vData As String) mvarFindMatchField = vDataEnd Property

Public Property Let FindRecordSource(ByVal vData As String) mvarFindRecordSource = vDataEnd Property

Public Property Let FindCaption(ByVal vData As String) mvarFindCaption = vDataEnd Property

Private Sub updateLabel(sLabelString As String)

Dim iIndx As Integer

With mvarFormName For iIndx = 0 To .Controls.Count - 1 If (.Controls(iIndx).Name = mvarLabelToUpdate) Then .Controls(iIndx).Caption = sLabelString Exit Sub End If NextEnd With

End Sub

Private Sub updateButtons(Optional vLockEm As Variant)On Error Resume NextDim sLabelString As String Select Case mvardataCtl.Recordset.EditMode

Case dbEditNone If (mvarTotalRecords > 1) Then If (mvardataCtl.Recordset.BOF) Or _ (mvardataCtl.Recordset.AbsolutePosition = 0) Then navigateButtons ("00111101011") ElseIf (mvardataCtl.Recordset.EOF) Or _(mvardataCtl.Recordset.AbsolutePosition = mvarTotalRecords - 1) Then navigateButtons ("11001101011") Else navigateButtons ("11111101011") End If ElseIf (mvarTotalRecords > 0) Then navigateButtons ("00001101001") Else navigateButtons ("00001000001") End If If (Not IsMissing(vLockEm)) Then lockTheControls (vLockEm) End If Case dbEditInProgress 'we are editing a current record Call lockTheControls(False) navigateButtons ("00000010100") Case dbEditAdd 'we are adding a new record Call lockTheControls(False) navigateButtons ("00000010100") End Select

mvarProgressBar.Value = mvardataCtl.Recordset.PercentPosition

sLabelString = mvardataCtl.Recordset.AbsolutePosition + 1sLabelString = sLabelString & " of " & mvarTotalRecordsCall updateLabel(sLabelString)End Sub

Private Sub navigateButtons(sButtonString As String)Dim iIndx As IntegerDim iButtonLength As Integer

sButtonString = Trim$(sButtonString)iButtonLength = Len(sButtonString)

For iIndx = 1 To iButtonLength If (Mid$(sButtonString, iIndx, 1) = "1") Then mvarFormName.Controls(mvarButtons)(iIndx - 1).Enabled = True Else mvarFormName.Controls(mvarButtons)(iIndx - 1).Enabled = False End IfNext

DoEvents

End Sub

Private Sub lockTheControls(bLocked As Boolean)

On Error Resume Next

Dim iIndx As Integer

With mvarFormName For iIndx = 0 To .Controls.Count - 1 If (.Controls(iIndx).Tag = mvarTag) Then If (TypeOf .Controls(iIndx) Is TextBox) Then If (bLocked) Then .Controls(iIndx).Locked = True .Controls(iIndx).BackColor = vbWhite Else .Controls(iIndx).Locked = False .Controls(iIndx).BackColor = vbYellow End If ElseIf (TypeOf .Controls(iIndx) Is DBGrid) Then If (bLocked) Then .Controls(iIndx).AllowAddNew = False .Controls(iIndx).AllowDelete = False .Controls(iIndx).AllowUpdate = False .Controls(iIndx).BackColor = vbWhite Else .Controls(iIndx).AllowAddNew = True .Controls(iIndx).AllowDelete = True .Controls(iIndx).AllowUpdate = True .Controls(iIndx).BackColor = vbYellow End If

End If End If NextEnd With

End Sub

Public Sub ProcessCMD(Index As Integer)Static vMyBookMark As VariantOn Error Resume Next

Select Case Index Case cmdMoveFirst '--- move first --- mvardataCtl.Recordset.MoveFirst Call updateButtons

Case cmdMovePrevious '--- move previous --- mvardataCtl.Recordset.MovePrevious Call updateButtons

Case cmdMoveNext '--- move next --- mvardataCtl.Recordset.MoveNext Call updateButtons

Case cmdMoveLast '-- move last --- mvardataCtl.Recordset.MoveLast Call updateButtons

'-- Now we are modifying the database -- Case cmdAddNew '-- add a new record With mvardataCtl.Recordset If (.EditMode = dbEditNone) Then If (mvarTotalRecords > 0) Then vMyBookMark = .Bookmark Else vMyBookMark = "" End If .AddNew Call updateButtons updateLabel ("Adding New Record") End If End With

Case cmdEdit '-- edit the current record With mvardataCtl.Recordset If (.EditMode = dbEditNone) Then vMyBookMark = .Bookmark .Edit Call updateButtons updateLabel ("Editing") End If End With

Case cmdSave '-- save the current record Dim bMoveLast As Boolean With mvardataCtl.Recordset If (.EditMode dbEditNone) Then If .EditMode = dbEditAdd Then bMoveLast = True Else bMoveLast = False End If .Update If (.EditMode = dbEditNone) Then mvarTotalRecords = .RecordCount If (bMoveLast = True) Then .MoveLast Else .Move 0 End If updateButtons True End If Else .Move 0 End If End With

Case cmdDelete '-- delete the current record Dim iResponse As Integer Dim sAskUser As String sAskUser = "Are you sure you want to delete this record?" iResponse = MsgBox(sAskUser, vbQuestion + vbYesNo + _ vbDefaultButton2, "Publishers Table") If (iResponse = vbYes) Then With mvardataCtl.Recordset .Delete mvarTotalRecords = .RecordCount If (mvarTotalRecords > 0) Then If mvarTotalRecords = 1 Then

.MoveNext

ElseIf .BOF Then

.MoveFirst Else .MovePrevious End If End If End With End If Call updateButtons

Case cmdUndo '-- undo changes to the current record With mvardataCtl.Recordset If (.EditMode dbEditNone) Then .CancelUpdate If (Len(vMyBookMark)) Then .Bookmark = vMyBookMark End If updateButtons True Else .Move 0 End If End With updateButtons True

Case cmdFind '-- find a specific record Dim iReturn As Integer gFindString = ""

With frmFind .addCaption = mvarFindCaption .RecordSource = mvarFindRecordSource .Show vbModal End With

If (Len(gFindString) > 0) Then Dim sResult As String With mvardataCtl.Recordset sResult = BuildCriteria() If Len(sResult) > 0 Then .FindFirst sResult If (.NoMatch) Then iReturn = MsgBox(mvarFindMatchField & " " & gFindString & _ " was not found.", vbCritical, App.EXEName) Else iReturn = MsgBox(mvarFindMatchField & " " & gFindString & _ " was retrieved.", vbInformation, App.EXEName) End If End If End With End If updateButtons

Case cmdDone '-- Done. Unload the form Unload mvarFormNameEnd SelectEnd Sub

Public Property Let Tag(ByVal vData As String)Attribute Tag.VB_Description = "The ID number of the bound controls" mvarTag = vDataEnd Property

Public Property Let RecordSource(ByVal vData As String)Attribute RecordSource.VB_Description = "The SQL command to retrieve the recordset" mvarRecordSource = vData If (mvardataCtl Is Nothing) Then Exit Property End If mvardataCtl.DatabaseName = mvardbName mvardataCtl.RecordSource = mvarRecordSource mvardataCtl.Refresh '-- Are there any records? -- If (mvardataCtl.Recordset.RecordCount < 1) Then mvarTotalRecords = 0 Exit Property End If

'-- There is at least 1 record -- Screen.MousePointer = vbHourglass mvardataCtl.Recordset.MoveLast mvarTotalRecords = mvardataCtl.Recordset.RecordCount mvardataCtl.Recordset.MoveFirst updateButtons 'added for child Screen.MousePointer = vbDefault

End Property

Public Property Set ProgressBar(ByVal vData As Object)Attribute ProgressBar.VB_Description = "Will manage the progress bar" Set mvarProgressBar = vDataEnd Property

Public Property Let LabelToUpdate(ByVal vData As String)Attribute LabelToUpdate.VB_Description = "The label on the form to put status information" mvarLabelToUpdate = vDataEnd Property

Public Property Set FormName(ByVal vData As Object)Attribute FormName.VB_Description = "The form that hosts the data control" Set mvarFormName = vDataEnd Property

Public Property Let dbName(ByVal vData As String)Attribute dbName.VB_Description = "The name of the database used" mvardbName = vDataEnd Property

Public Property Let Buttons(ByVal vData As String)Attribute Buttons.VB_Description = "The string to handle the buttons in the array" mvarButtons = vDataEnd Property

Public Property Set dataCtl(ByVal vData As Object)Attribute dataCtl.VB_Description = "The data control that the class is operating on." Set mvardataCtl = vData mvardataCtl.RecordsetType = 1 'ensure a dynaset for abspositionEnd Property

Chapter7/Page330/frmDataClass.frmVERSION 5.00Object = "{00028C01-0000-0000-0000-000000000046}#1.0#0"; "DBGRID32.OCX"Object = "{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}#2.0#0"; "MSCOMCTL.OCX"Begin VB.Form frmDataClass Caption = "Easy Data Entry Grid Example" ClientHeight = 5280 ClientLeft = 60 ClientTop = 345 ClientWidth = 7020 LinkTopic = "Form1" ScaleHeight = 5280 ScaleWidth = 7020 StartUpPosition = 3 'Windows Default Begin MSComctlLib.ProgressBar ProgressBar1 Align = 2 'Align Bottom Height = 255 Left = 0 TabIndex = 27 Top = 5025 Width = 7020 _ExtentX = 12383 _ExtentY = 450 _Version = 393216 Appearance = 1 End Begin MSDBGrid.DBGrid DBGrid1 Bindings = "frmDataClass.frx":0000 Height = 2175 Left = 120 OleObjectBlob = "frmDataClass.frx":0014 TabIndex = 26 Tag = "2" Top = 1440 Width = 6735 End Begin VB.CommandButton cmdTitles Caption = "D&one" Height = 495 Index = 10 Left = 5880 TabIndex = 24 Top = 4440 Width = 975 End Begin VB.CommandButton cmdTitles Caption = "&Find" Height = 495 Index = 9 Left = 120 TabIndex = 23 Top = 5400 Width = 975 End Begin VB.CommandButton cmdTitles Caption = "&Undo" Height = 495 Index = 8 Left = 3960 TabIndex = 22 Top = 4440 Width = 975 End Begin VB.CommandButton cmdTitles Caption = "&Delete" Height = 495 Index = 7 Left = 3000 TabIndex = 21 Top = 4440 Width = 975 End Begin VB.CommandButton cmdTitles Caption = "&Save" Height = 495 Index = 6 Left = 2040 TabIndex = 20 Top = 4440 Width = 975 End Begin VB.CommandButton cmdTitles Caption = "&Edit" Height = 495 Index = 5 Left = 1080 TabIndex = 19 Top = 4440 Width = 975 End Begin VB.CommandButton cmdTitles Caption = "&Add New" Height = 495 Index = 4 Left = 120 TabIndex = 18 Top = 4440 Width = 975 End Begin VB.CommandButton cmdTitles Caption = ">>|" Height = 495 Index = 3 Left = 3000 TabIndex = 17 Top = 3720 Width = 975 End Begin VB.CommandButton cmdTitles Caption = ">>" Height = 495 Index = 2 Left = 2040 TabIndex = 16 Top = 3720 Width = 975 End Begin VB.CommandButton cmdTitles Caption = " 0) Then If mvarTotalRecords = 1 Then

.MoveNext

ElseIf .BOF Then

.MoveFirst Else .MovePrevious End If End If End With End If Call updateButtons

Case cmdUndo '-- undo changes to the current record With mvardataCtl.Recordset If (.EditMode dbEditNone) Then .CancelUpdate If (Len(vMyBookMark)) Then .Bookmark = vMyBookMark End If updateButtons True Else .Move 0 End If End With updateButtons True

Case cmdFind '-- find a specific record Dim iReturn As Integer gFindString = ""

With frmFind .addCaption = mvarFindCaption .RecordSource = mvarFindRecordSource .Show vbModal End With

If (Len(gFindString) > 0) Then Dim sResult As String With mvardataCtl.Recordset sResult = BuildCriteria() If Len(sResult) > 0 Then .FindFirst sResult If (.NoMatch) Then iReturn = MsgBox(mvarFindMatchField & " " & gFindString & _ " was not found.", vbCritical, App.EXEName) Else iReturn = MsgBox(mvarFindMatchField & " " & gFindString & _ " was retrieved.", vbInformation, App.EXEName) End If End If End With End If updateButtons

Case cmdDone '-- Done. Unload the form Unload mvarFormNameEnd SelectEnd Sub

Public Property Let Tag(ByVal vData As String)Attribute Tag.VB_Description = "The ID number of the bound controls" mvarTag = vDataEnd Property

Public Property Let RecordSource(ByVal vData As String)Attribute RecordSource.VB_Description = "The SQL command to retrieve the recordset" mvarRecordSource = vData If (mvardataCtl Is Nothing) Then Exit Property End If mvardataCtl.DatabaseName = mvardbName mvardataCtl.RecordSource = mvarRecordSource mvardataCtl.Refresh '-- Are there any records? -- If (mvardataCtl.Recordset.RecordCount < 1) Then mvarTotalRecords = 0 Exit Property End If

'-- There is at least 1 record -- Screen.MousePointer = vbHourglass mvardataCtl.Recordset.MoveLast mvarTotalRecords = mvardataCtl.Recordset.RecordCount mvardataCtl.Recordset.MoveFirst Screen.MousePointer = vbDefault

End Property

Public Property Set ProgressBar(ByVal vData As Object)Attribute ProgressBar.VB_Description = "Will manage the progress bar" Set mvarProgressBar = vDataEnd Property

Public Property Let LabelToUpdate(ByVal vData As String)Attribute LabelToUpdate.VB_Description = "The label on the form to put status information" mvarLabelToUpdate = vDataEnd Property

Public Property Set FormName(ByVal vData As Object)Attribute FormName.VB_Description = "The form that hosts the data control" Set mvarFormName = vDataEnd Property

Public Property Let dbName(ByVal vData As String)Attribute dbName.VB_Description = "The name of the database used" mvardbName = vDataEnd Property

Public Property Let Buttons(ByVal vData As String)Attribute Buttons.VB_Description = "The string to handle the buttons in the array" mvarButtons = vDataEnd Property

Public Property Set dataCtl(ByVal vData As Object)Attribute dataCtl.VB_Description = "The data control that the class is operating on." Set mvardataCtl = vData mvardataCtl.RecordsetType = 1 'ensure a dynaset for abspositionEnd Property

Chapter7/Page320/frmDataClass.frmVERSION 5.00Object = "{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}#2.0#0"; "MSCOMCTL.OCX"Begin VB.Form frmDataClass Caption = "Template form for our dataClass" ClientHeight = 3540 ClientLeft = 60 ClientTop = 345 ClientWidth = 6585 LinkTopic = "Form1" ScaleHeight = 3540 ScaleWidth = 6585 StartUpPosition = 3 'Windows Default Begin VB.TextBox Text4 DataField = "PubID" DataSource = "Data1" Height = 375 Left = 120 Locked = -1 'True TabIndex = 16 Text = "PubID" Top = 360 Width = 1215 End Begin VB.TextBox Text3 DataField = "ISBN" DataSource = "Data1" Height = 405 Left = 2160 TabIndex = 15 Tag = "1" Text = "ISBN" Top = 360 Width = 1815 End Begin VB.TextBox Text2 DataField = "Year Published" DataSource = "Data1" Height = 375 Left = 5280 TabIndex = 14 Tag = "1" Text = "Year Published" Top = 360 Width = 1215 End Begin VB.TextBox Text1 DataField = "Title" DataSource = "Data1" Height = 375 Left = 120 TabIndex = 13 Tag = "1" Text = "Title" Top = 1440 Width = 4815 End Begin VB.Data Data1 Caption = "Data1" Connect = "Access" DatabaseName = "" DefaultCursorType= 0 'DefaultCursor DefaultType = 2 'UseODBC Exclusive = 0 'False Height = 345 Left = 3240 Options = 0 ReadOnly = 0 'False RecordsetType = 1 'Dynaset RecordSource = "" Top = 840 Visible = 0 'False Width = 1860 End Begin VB.CommandButton cmdButton Caption = "||" Height = 495 Index = 3 Left = 3000 TabIndex = 7 Top = 2640 Width = 975 End Begin VB.CommandButton cmdButton Caption = "&Add New" Height = 495 Index = 4 Left = 120 TabIndex = 6 Top = 2040 Width = 975 End Begin VB.CommandButton cmdButton Caption = "&Edit" Height = 495 Index = 5 Left = 3360 TabIndex = 5 Top = 2040 Width = 975 End Begin VB.CommandButton cmdButton Caption = "&Save" Height = 495 Index = 6 Left = 1200 TabIndex = 4 Top = 2040 Width = 975 End Begin VB.CommandButton cmdButton Caption = "&Delete" Height = 495 Index = 7 Left = 4440 TabIndex = 3 Top = 2040 Width = 975 End Begin VB.CommandButton cmdButton Caption = "&Undo" Height = 495 Index = 8 Left = 2280 TabIndex = 2 Top = 2040 Width = 975 End Begin VB.CommandButton cmdButton Caption = "&Find" Height = 495 Index = 9 Left = 5520 TabIndex = 1 Top = 2040 Width = 975 End Begin VB.CommandButton cmdButton Caption = "D&one" Height = 495 Index = 10 Left = 5520 TabIndex = 0 Top = 2640 Width = 975 End Begin MSComctlLib.ProgressBar ProgressBar1 Align = 2 'Align Bottom Height = 255 Left = 0 TabIndex = 11 Top = 3285 Width = 6585 _ExtentX = 11615 _ExtentY = 450 _Version = 393216 Appearance = 1 End Begin VB.Label Label4 Caption = "Book Title" Height = 255 Left = 120 TabIndex = 20 Top = 1200 Width = 1815 End Begin VB.Label Label3 Caption = "Year Published" Height = 255 Left = 5280 TabIndex = 19 Top = 120 Width = 1215 End Begin VB.Label Label2 Caption = "ISBN" Height = 255 Left = 2160 TabIndex = 18 Top = 120 Width = 975 End Begin VB.Label Label1 Caption = "Publisher's ID" Height = 255 Left = 120 TabIndex = 17 Top = 120 Width = 1215 End Begin VB.Label lblRecordCount BorderStyle = 1 'Fixed Single Caption = "lblRecordCount" Height = 375 Left = 4080 TabIndex = 12 Top = 2760 Width = 1335 EndEndAttribute VB_Name = "frmDataClass"Attribute VB_GlobalNameSpace = FalseAttribute VB_Creatable = FalseAttribute VB_PredeclaredId = TrueAttribute VB_Exposed = FalseOption ExplicitDim myDataClass As dataClass

Private Sub cmdButton_Click(Index As Integer)Text3.SetFocusmyDataClass.ProcessCMD IndexEnd Sub

Private Sub Form_Activate()

Static blnIsOld As Boolean 'the default value of a Boolean is False

If blnIsOld = False Then Set myDataClass = New dataClass With myDataClass Set .FormName = Me 'pass in the current form Set .dataCtl = Data1 'the data control to manage Set .ProgressBar = ProgressBar1 .dbName = gDataBaseName .Buttons = "cmdButton" .RecordSource = "SELECT * FROM Titles" .LabelToUpdate = lblRecordCount .FindCaption = "Select a Book Title" .FindRecordSource = "SELECT Title FROM Titles ORDER BY Title" .FindMatchField = "Title"

.Tag = "1" 'identifies the controls .ProcessCMD 0 'default to the 1st recordEnd With

Text3.SetFocusblnIsOld = TrueEnd If

End Sub

Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)Dim iMessage As Integer

If (Data1.Recordset.EditMode dbEditNone) Then iMessage = MsgBox("You must complete editing the current record", _ vbInformation, App.EXEName) Cancel = TrueEnd If

End Sub

Private Sub Text1_GotFocus() highLightEnd Sub

Private Sub Text2_GotFocus() highLightEnd Sub

Private Sub Text3_GotFocus() highLightEnd Sub

Private Sub Text4_GotFocus() highLightEnd Sub

Chapter7/Page320/frmFind.frmVERSION 5.00Begin VB.Form frmFind BorderStyle = 3 'Fixed Dialog Caption = "Find Record" ClientHeight = 5400 ClientLeft = 45 ClientTop = 330 ClientWidth = 4830 LinkTopic = "Form2" MaxButton = 0 'False MinButton = 0 'False ScaleHeight = 5400 ScaleWidth = 4830 ShowInTaskbar = 0 'False StartUpPosition = 3 'Windows Default Begin VB.Timer Timer1 Left = 4080 Top = 600 End Begin VB.Data dtaFind Caption = "Data1" Connect = "Access" DatabaseName = "" DefaultCursorType= 0 'DefaultCursor DefaultType = 2 'UseODBC Exclusive = 0 'False Height = 300 Left = 3240 Options = 0 ReadOnly = 0 'False RecordsetType = 1 'Dynaset RecordSource = "" Top = 4440 Visible = 0 'False Width = 1215 End Begin VB.CommandButton cmdCancel Caption = "&Cancel" Height = 495 Left = 1800 TabIndex = 5 Top = 4440 Width = 1215 End Begin VB.ListBox List1 Height = 2205 Left = 360 TabIndex = 3 Top = 1200 Width = 4095 End Begin VB.TextBox txtFind Height = 285 Left = 360 TabIndex = 2 Top = 720 Width = 1575 End Begin VB.Label lblCaption Alignment = 2 'Center Caption = "Double-click to select" ForeColor = &H00FF0000& Height = 255 Left = 360 TabIndex = 4 Top = 3480 Width = 4095 End Begin VB.Label lblCount Alignment = 2 'Center BorderStyle = 1 'Fixed Single Caption = "lblCount" Height = 255 Left = 360 TabIndex = 1 Top = 3840 Width = 4095 End Begin VB.Label lblWhichTable Caption = "lblWhichTable" Height = 255 Left = 360 TabIndex = 0 Top = 240 Width = 4095 EndEndAttribute VB_Name = "frmFind"Attribute VB_GlobalNameSpace = FalseAttribute VB_Creatable = FalseAttribute VB_PredeclaredId = TrueAttribute VB_Exposed = FalsePrivate Sub cmdCancel_Click()Unload MeEnd Sub

Private Sub Form_Activate()List1.Enabled = FalsedtaFind.DatabaseName = gDataBaseNamedtaFind.RefreshIf (dtaFind.Recordset.RecordCount > 0) Then Screen.MousePointer = vbHourglass dtaFind.Recordset.MoveFirst While Not dtaFind.Recordset.EOF List1.AddItem dtaFind.Recordset.Fields(0) & "" dtaFind.Recordset.MoveNext Wend List1.Enabled = True DoEventsEnd If

lblCount = "There are " & dtaFind.Recordset.RecordCount & " records"Screen.MousePointer = vbDefault

End Sub

Public Property Let RecordSource(ByVal sNewValue As String) dtaFind.RecordSource = sNewValueEnd Property

Public Property Let addCaption(ByVal sNewValue As String) lblWhichTable = sNewValueEnd Property

Private Sub Form_Load()Timer1.Enabled = FalseTimer1.Interval = 1

End Sub

Private Sub Form_Unload(Cancel As Integer)Set frmFind = NothingEnd Sub

Private Sub List1_DblClick()'get the item the user clicks on and assign itIf (InStr(List1, "'")) Then gFindString = SrchReplace(List1)Else gFindString = List1End If

Timer1.Enabled = True

End Sub

Private Sub Timer1_Timer()Timer1.Enabled = FalseUnload Me

End Sub

Private Sub txtFind_Change()Dim entryNum As LongDim txtToFind As StringtxtToFind = txtFind.Text

entryNum = sendMessageByString(List1.hwnd, _ LB_SELECTSTRING, 0, txtToFind)

End Sub

Function SrchReplace(ByVal sStringToFix As String) As String

Dim iPosition As Integer 'where is the offending char?Dim sCharToReplace As String 'which char do we want to replace?Dim sReplaceWith As String 'what should it be replaced with?Dim sTempString As String 'build the correct returned string

sCharToReplace = "'"sReplaceWith = "''"

iPosition = InStr(sStringToFix, sCharToReplace)sTempString = ""

Do While iPosition sTempString = sTempString & Left$(sStringToFix, iPosition - 1) sTempString = sTempString & sReplaceWith sTempString = sTempString & _ Mid$(sStringToFix, iPosition + 1, Len(sStringToFix)) iPosition = InStr(iPosition + 1, sStringToFix, sCharToReplace)Loop

SrchReplace = sTempString

End Function

Chapter7/Page320/Globals.basAttribute VB_Name = "Globals"Option Explicit

Public Declare Function sendMessageByString& Lib "user32" _ Alias "SendMessageA" (ByVal hwnd As Long, _ ByVal wMsg As Long, ByVal wParam As Long, _ ByVal lParam As String)

Public Const LB_SELECTSTRING = &H18CPublic gFindString As StringPublic Const gDataBaseName = "C:\BegDB\Biblio.mdb"

Public Sub highLight()

If (Not Screen.ActiveForm Is Nothing) ThenWith Screen.ActiveForm If (TypeOf .ActiveControl Is TextBox) Then .ActiveControl.SelStart = 0 .ActiveControl.SelLength = Len(.ActiveControl) End If

End WithEnd IfEnd Sub

Chapter7/Page320/NewDataClass.exe

Chapter7/Page320/NewDataClass.vbpType=ExeReference=*\G{00020430-0000-0000-C000-000000000046}#2.0#0#..\..\..\WINDOWS\SYSTEM\StdOle2.Tlb#OLE AutomationReference=*\G{00025E01-0000-0000-C000-000000000046}#4.0#0#..\..\..\PROGRAM FILES\COMMON FILES\MICROSOFT SHARED\DAO\DAO350.DLL#Microsoft DAO 3.51 Object LibraryObject={831FDD16-0C5C-11D2-A9FC-0000F8754DA1}#2.0#0; MSCOMCTL.OCXForm=frmDataClass.frmForm=frmFind.frmClass=dataClass; dataClass.clsModule=Globals; Globals.basStartup="frmDataClass"HelpFile=""ExeName32="NewDataClass.exe"Command32=""Name="Project1"HelpContextID="0"CompatibleMode="0"MajorVer=1MinorVer=0RevisionVer=0AutoIncrementVer=0ServerSupportFiles=0VersionCompanyName="Wrox Press"CompilationType=0OptimizationType=0FavorPentiumPro(tm)=0CodeViewDebugInfo=0NoAliasing=0BoundsCheck=0OverflowCheck=0FlPointCheck=0FDIVCheck=0UnroundedFP=0StartMode=0Unattended=0Retained=0ThreadPerObject=0MaxNumberOfThreads=1

[MS Transaction Server]AutoRefresh=1

Chapter7/Page320/NewDataClass.vbwfrmDataClass = 0, 0, 0, 0, C, 22, 29, 743, 650, CfrmFind = 0, 0, 0, 0, C, 44, 58, 765, 679, CdataClass = 0, 0, 0, 0, CGlobals = 0, 0, 0, 0, C

Chapter7/Page276/dataClass.clsVERSION 1.0 CLASSBEGIN MultiUse = -1 'True Persistable = 0 'NotPersistable DataBindingBehavior = 0 'vbNone DataSourceBehavior = 0 'vbNone MTSTransactionMode = 0 'NotAnMTSObjectENDAttribute VB_Name = "dataClass"Attribute VB_GlobalNameSpace = FalseAttribute VB_Creatable = TrueAttribute VB_PredeclaredId = FalseAttribute VB_Exposed = FalseAttribute VB_Description = "This class is used to manage the functionality of a data control. It can instantiated in a form and will then handle an associated data control."Attribute VB_Ext_KEY = "SavedWithClassBuilder6" ,"Yes"Attribute VB_Ext_KEY = "Top_Level" ,"Yes"Option Explicit

'local variable(s) to hold property value(s)Private mvardataCtl As Object 'local copyPrivate mvarButtons As String 'local copyPrivate mvardbName As String 'local copyPrivate mvarFormName As Object 'local copyPrivate mvarLabelToUpdate As String 'local copyPrivate mvarProgressBar As Object 'local copyPrivate mvarRecordSource As String 'local copyPrivate mvarTag As String 'local copyPrivate mvarTotalRecords As Long

Private Enum cmdButtons cmdMoveFirst = 0 cmdMovePrevious = 1 cmdMoveNext = 2 cmdMoveLast = 3 cmdAddNew = 4 cmdEdit = 5 cmdSave = 6 cmdDelete = 7 cmdUndo = 8 cmdFind = 9 cmdDone = 10End Enum

'local variable(s) to hold property value(s)Private mvarFindCaption As String 'local copyPrivate mvarFindRecordSource As String 'local copyPrivate mvarFindMatchField As String 'local copy

Private Function BuildCriteria() As String

Dim sCriteria As String Dim fField As Field Dim sMessage As String Dim iIndx As Integer Set fField = mvardataCtl.Recordset.Fields(mvarFindMatchField) Select Case fField.Type Case dbInteger, dbLong, dbCurrency, dbSingle, dbDouble BuildCriteria = "" & mvarFindMatchField & " = " & gFindString Case dbDate BuildCriteria = "" & mvarFindMatchField & " = #" & gFindString & "#" Case dbText BuildCriteria = "" & mvarFindMatchField & " = '" & gFindString & "'" Case Else sMessage = "Sorry, you can't use the find feature on fields" sMessage = sMessage & " of type: " & fField.Type iIndx = MsgBox(sMessage, vbCritical, App.EXEName)End SelectEnd Function

Public Property Let FindMatchField(ByVal vData As String) mvarFindMatchField = vDataEnd Property

Public Property Let FindRecordSource(ByVal vData As String) mvarFindRecordSource = vDataEnd Property

Public Property Let FindCaption(ByVal vData As String) mvarFindCaption = vDataEnd Property

Private Sub updateLabel(sLabelString As String)

Dim iIndx As Integer

With mvarFormName For iIndx = 0 To .Controls.Count - 1 If (.Controls(iIndx).Name = mvarLabelToUpdate) Then .Controls(iIndx).Caption = sLabelString Exit Sub End If NextEnd With

End Sub

Private Sub updateButtons(Optional vLockEm As Variant)Dim sLabelString As String Select Case mvardataCtl.Recordset.EditMode

Case dbEditNone If (mvarTotalRecords > 2) Then If (mvardataCtl.Recordset.BOF) Or _ (mvardataCtl.Recordset.AbsolutePosition = 0) Then navigateButtons ("00111101011") ElseIf (mvardataCtl.Recordset.EOF) Or _(mvardataCtl.Recordset.AbsolutePosition = mvarTotalRecords - 1) Then navigateButtons ("11001101011") Else navigateButtons ("11111101011") End If ElseIf (mvarTotalRecords > 0) Then navigateButtons ("00001101001") Else navigateButtons ("00001000001") End If If (Not IsMissing(vLockEm)) Then lockTheControls (vLockEm) End If Case dbEditInProgress 'we are editing a current record Call lockTheControls(False) navigateButtons ("00000010100") Case dbEditAdd 'we are adding a new record Call lockTheControls(False) navigateButtons ("00000010100") End Select

mvarProgressBar.Value = mvardataCtl.Recordset.PercentPosition

sLabelString = mvardataCtl.Recordset.AbsolutePosition + 1sLabelString = sLabelString & " of " & mvarTotalRecordsCall updateLabel(sLabelString)End Sub

Private Sub navigateButtons(sButtonString As String)Dim iIndx As IntegerDim iButtonLength As Integer

sButtonString = Trim$(sButtonString)iButtonLength = Len(sButtonString)

For iIndx = 1 To iButtonLength If (Mid$(sButtonString, iIndx, 1) = "1") Then mvarFormName.Controls(mvarButtons)(iIndx - 1).Enabled = True Else mvarFormName.Controls(mvarButtons)(iIndx - 1).Enabled = False End IfNext

DoEvents

End Sub

Private Sub lockTheControls(bLocked As Boolean)

On Error Resume Next

Dim iIndx As Integer

With mvarFormName For iIndx = 0 To .Controls.Count - 1 If (.Controls(iIndx).Tag = mvarTag) Then If (TypeOf .Controls(iIndx) Is TextBox) Then If (bLocked) Then .Controls(iIndx).Locked = True .Controls(iIndx).BackColor = vbWhite Else .Controls(iIndx).Locked = False .Controls(iIndx).BackColor = vbYellow End If End If End If NextEnd With

End Sub

Public Sub ProcessCMD(Index As Integer)Static vMyBookMark As VariantOn Error Resume Next

Select Case Index Case cmdMoveFirst '--- move first --- mvardataCtl.Recordset.MoveFirst Call updateButtons

Case cmdMovePrevious '--- move previous --- mvardataCtl.Recordset.MovePrevious Call updateButtons

Case cmdMoveNext '--- move next --- mvardataCtl.Recordset.MoveNext Call updateButtons

Case cmdMoveLast '-- move last --- mvardataCtl.Recordset.MoveLast Call updateButtons

'-- Now we are modifying the database -- Case cmdAddNew '-- add a new record With mvardataCtl.Recordset If (.EditMode = dbEditNone) Then If (mvarTotalRecords > 0) Then vMyBookMark = .Bookmark Else vMyBookMark = "" End If .AddNew Call updateButtons updateLabel ("Adding New Record") End If End With

Case cmdEdit '-- edit the current record With mvardataCtl.Recordset If (.EditMode = dbEditNone) Then vMyBookMark = .Bookmark .Edit Call updateButtons updateLabel ("Editing") End If End With

Case cmdSave '-- save the current record Dim bMoveLast As Boolean With mvardataCtl.Recordset If (.EditMode dbEditNone) Then If .EditMode = dbEditAdd Then bMoveLast = True Else bMoveLast = False End If .Update If (.EditMode = dbEditNone) Then mvarTotalRecords = .RecordCount If (bMoveLast = True) Then .MoveLast Else .Move 0 End If updateButtons True End If Else .Move 0 End If End With

Case cmdDelete '-- delete the current record Dim iResponse As Integer Dim sAskUser As String sAskUser = "Are you sure you want to delete this record?" iResponse = MsgBox(sAskUser, vbQuestion + vbYesNo + _ vbDefaultButton2, "Publishers Table") If (iResponse = vbYes) Then With mvardataCtl.Recordset .Delete mvarTotalRecords = .RecordCount If (mvarTotalRecords > 0) Then If mvarTotalRecords = 1 Then

.MoveNext

ElseIf .BOF Then

.MoveFirst Else .MovePrevious End If End If End With End If Call updateButtons

Case cmdUndo '-- undo changes to the current record With mvardataCtl.Recordset If (.EditMode dbEditNone) Then .CancelUpdate If (Len(vMyBookMark)) Then .Bookmark = vMyBookMark End If updateButtons True Else .Move 0 End If End With updateButtons True

Case cmdFind '-- find a specific record Dim iReturn As Integer gFindString = ""

With frmFind .addCaption = mvarFindCaption .RecordSource = mvarFindRecordSource .Show vbModal End With

If (Len(gFindString) > 0) Then With mvardataCtl.Recordset .FindFirst BuildCriteria() If (.NoMatch) Then iReturn = MsgBox(mvarFindMatchField & " " & gFindString & _ " was not found.", vbCritical, App.EXEName) Else iReturn = MsgBox(mvarFindMatchField & " " & gFindString & _ " was retrieved.", vbInformation, App.EXEName) End If End With End If updateButtons

Case cmdDone '-- Done. Unload the form Unload mvarFormNameEnd SelectEnd Sub

Public Property Let Tag(ByVal vData As String)Attribute Tag.VB_Description = "The ID number of the bound controls" mvarTag = vDataEnd Property

Public Property Let RecordSource(ByVal vData As String)Attribute RecordSource.VB_Description = "The SQL command to retrieve the recordset" mvarRecordSource = vData If (mvardataCtl Is Nothing) Then Exit Property End If mvardataCtl.DatabaseName = mvardbName mvardataCtl.RecordSource = mvarRecordSource mvardataCtl.Refresh '-- Are there any records? -- If (mvardataCtl.Recordset.RecordCount < 1) Then mvarTotalRecords = 0 Exit Property End If

'-- There is at least 1 record -- Screen.MousePointer = vbHourglass mvardataCtl.Recordset.MoveLast mvarTotalRecords = mvardataCtl.Recordset.RecordCount mvardataCtl.Recordset.MoveFirst Screen.MousePointer = vbDefault

End Property

Public Property Set ProgressBar(ByVal vData As Object)Attribute ProgressBar.VB_Description = "Will manage the progress bar" Set mvarProgressBar = vDataEnd Property

Public Property Let LabelToUpdate(ByVal vData As String)Attribute LabelToUpdate.VB_Description = "The label on the form to put status information" mvarLabelToUpdate = vDataEnd Property

Public Property Set FormName(ByVal vData As Object)Attribute FormName.VB_Description = "The form that hosts the data control" Set mvarFormName = vDataEnd Property

Public Property Let dbName(ByVal vData As String)Attribute dbName.VB_Description = "The name of the database used" mvardbName = vDataEnd Property

Public Property Let Buttons(ByVal vData As String)Attribute Buttons.VB_Description = "The string to handle the buttons in the array" mvarButtons = vDataEnd Property

Public Property Set dataCtl(ByVal vData As Object)Attribute dataCtl.VB_Description = "The data control that the class is operating on." Set mvardataCtl = vData mvardataCtl.RecordsetType = 1 'ensure a dynaset for abspositionEnd Property

Chapter7/Page276/frmDataClass.frmVERSION 5.00Object = "{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}#2.0#0"; "MSCOMCTL.OCX"Begin VB.Form frmDataClass Caption = "Template form for our dataClass" ClientHeight = 2310 ClientLeft = 60 ClientTop = 345 ClientWidth = 6585 LinkTopic = "Form1" ScaleHeight = 2310 ScaleWidth = 6585 StartUpPosition = 3 'Windows Default Begin VB.TextBox Text1 DataSource = "Data1" Height = 375 Left = 2400 TabIndex = 13 Tag = "1" Text = "Text1" Top = 240 Width = 1935 End Begin VB.Data Data1 Caption = "Data1" Connect = "Access" DatabaseName = "" DefaultCursorType= 0 'DefaultCursor DefaultType = 2 'UseODBC Exclusive = 0 'False Height = 300 Left = 240 Options = 0 ReadOnly = 0 'False RecordsetType = 1 'Dynaset RecordSource = "" Top = 240 Visible = 0 'False Width = 1860 End Begin VB.CommandButton cmdButton Caption = "||" Height = 495 Index = 3 Left = 3000 TabIndex = 7 Top = 1440 Width = 975 End Begin VB.CommandButton cmdButton Caption = "&Add New" Height = 495 Index = 4 Left = 120 TabIndex = 6 Top = 720 Width = 975 End Begin VB.CommandButton cmdButton Caption = "&Edit" Height = 495 Index = 5 Left = 3360 TabIndex = 5 Top = 720 Width = 975 End Begin VB.CommandButton cmdButton Caption = "&Save" Height = 495 Index = 6 Left = 1200 TabIndex = 4 Top = 720 Width = 975 End Begin VB.CommandButton cmdButton Caption = "&Delete" Height = 495 Index = 7 Left = 4440 TabIndex = 3 Top = 720 Width = 975 End Begin VB.CommandButton cmdButton Caption = "&Undo" Height = 495 Index = 8 Left = 2280 TabIndex = 2 Top = 720 Width = 975 End Begin VB.CommandButton cmdButton Caption = "&Find" Height = 495 Index = 9 Left = 5520 TabIndex = 1 Top = 720 Width = 975 End Begin VB.CommandButton cmdButton Caption = "D&one" Height = 495 Index = 10 Left = 5520 TabIndex = 0 Top = 1440 Width = 975 End Begin MSComctlLib.ProgressBar ProgressBar1 Align = 2 'Align Bottom Height = 255 Left = 0 TabIndex = 11 Top = 2055 Width = 6585 _ExtentX = 11615 _ExtentY = 450 _Version = 393216 Appearance = 1 End Begin VB.Label lblRecordCount BorderStyle = 1 'Fixed Single Caption = "lblRecordCount" Height = 375 Left = 4080 TabIndex = 12 Top = 1560 Width = 1335 EndEndAttribute VB_Name = "frmDataClass"Attribute VB_GlobalNameSpace = FalseAttribute VB_Creatable = FalseAttribute VB_PredeclaredId = TrueAttribute VB_Exposed = FalseOption ExplicitDim myDataClass As dataClass

Private Sub cmdButton_Click(Index As Integer)myDataClass.ProcessCMD (Index)End Sub

Private Sub Form_Activate()

Static blnIsOld As Boolean 'the default value of a Boolean is False

If blnIsOld = False Then

Set myDataClass = New dataClass With myDataClass Set .FormName = Me 'pass in the current form Set .dataCtl = Data1 'the data control to manage Set .ProgressBar = ProgressBar1 .dbName = gDataBaseName .Buttons = "cmdButton" .RecordSource = "SELECT * FROM Publishers" .LabelToUpdate = lblRecordCount .FindCaption = "Select a Publisher's ID" .FindRecordSource = "SELECT PubID FROM Publishers" .FindMatchField = "PubID"

.Tag = "1" 'identifies the controls .ProcessCMD 0 'default to the 1st recordEnd With

blnIsOld = TrueEnd If

Text1.DataField = "Name"

If (Data1.Recordset.EditMode = dbEditNone) Then Text1.Locked = TrueEnd If

End Sub

Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)Dim iMessage As Integer

If (Data1.Recordset.EditMode dbEditNone) Then iMessage = MsgBox("You must complete editing the current record", _ vbInformation, App.EXEName) Cancel = TrueEnd If

End Sub

Chapter7/Page276/frmFind.frmVERSION 5.00Begin VB.Form frmFind BorderStyle = 3 'Fixed Dialog Caption = "Find Record" ClientHeight = 5400 ClientLeft = 45 ClientTop = 330 ClientWidth = 4830 LinkTopic = "Form2" MaxButton = 0 'False MinButton = 0 'False ScaleHeight = 5400 ScaleWidth = 4830 ShowInTaskbar = 0 'False StartUpPosition = 3 'Windows Default Begin VB.Timer Timer1 Left = 3840 Top = 720 End Begin VB.Data dtaFind Caption = "Data1" Connect = "Access" DatabaseName = "" DefaultCursorType= 0 'DefaultCursor DefaultType = 2 'UseODBC Exclusive = 0 'False Height = 300 Left = 3240 Options = 0 ReadOnly = 0 'False RecordsetType = 1 'Dynaset RecordSource = "" Top = 4440 Visible = 0 'False Width = 1215 End Begin VB.CommandButton cmdCancel Caption = "&Cancel" Height = 495 Left = 1800 TabIndex = 5 Top = 4440 Width = 1215 End Begin VB.ListBox List1 Height = 2205 Left = 360 TabIndex = 3 Top = 1200 Width = 4095 End Begin VB.TextBox txtFind Height = 285 Left = 360 TabIndex = 2 Top = 720 Width = 1575 End Begin VB.Label lblCaption Alignment = 2 'Center Caption = "Double-click to select" ForeColor = &H00FF0000& Height = 255 Left = 360 TabIndex = 4 Top = 3480 Width = 4095 End Begin VB.Label lblCount Alignment = 2 'Center BorderStyle = 1 'Fixed Single Caption = "lblCount" Height = 255 Left = 360 TabIndex = 1 Top = 3840 Width = 4095 End Begin VB.Label lblWhichTable Caption = "lblWhichTable" Height = 255 Left = 360 TabIndex = 0 Top = 240 Width = 4095 EndEndAttribute VB_Name = "frmFind"Attribute VB_GlobalNameSpace = FalseAttribute VB_Creatable = FalseAttribute VB_PredeclaredId = TrueAttribute VB_Exposed = FalsePrivate Sub cmdCancel_Click()Unload MeEnd Sub

Private Sub Form_Activate()List1.Enabled = FalsedtaFind.DatabaseName = gDataBaseNamedtaFind.RefreshIf (dtaFind.Recordset.RecordCount > 0) Then Screen.MousePointer = vbHourglass dtaFind.Recordset.MoveFirst While Not dtaFind.Recordset.EOF List1.AddItem dtaFind.Recordset.Fields(0) & "" dtaFind.Recordset.MoveNext Wend List1.Enabled = True DoEventsEnd If

lblCount = "There are " & dtaFind.Recordset.RecordCount & " records"Screen.MousePointer = vbDefault

End Sub

Public Property Let RecordSource(ByVal sNewValue As String) dtaFind.RecordSource = sNewValueEnd Property

Public Property Let addCaption(ByVal sNewValue As String) lblWhichTable = sNewValueEnd Property

Private Sub Form_Load()Timer1.Enabled = FalseTimer1.Interval = 1

End Sub

Private Sub Form_Unload(Cancel As Integer)Set frmFind = NothingEnd Sub

Private Sub List1_DblClick()'get the item the user clicks on and assign itIf (InStr(List1, "'")) Then gFindString = SrchReplace(List1)Else gFindString = List1End If

Timer1.Enabled = True

End Sub

Private Sub Timer1_Timer()Timer1.Enabled = FalseUnload Me

End Sub

Private Sub txtFind_Change()Dim entryNum As LongDim txtToFind As StringtxtToFind = txtFind.Text

entryNum = sendMessageByString(List1.hwnd, _ LB_SELECTSTRING, 0, txtToFind)

End Sub

Function SrchReplace(ByVal sStringToFix As String) As String

Dim iPosition As Integer 'where is the offending char?Dim sCharToReplace As String 'which char do we want to replace?Dim sReplaceWith As String 'what should it be replaced with?Dim sTempString As String 'build the correct returned string

sCharToReplace = "'"sReplaceWith = "''"

iPosition = InStr(sStringToFix, sCharToReplace)sTempString = ""

Do While iPosition sTempString = sTempString & Left$(sStringToFix, iPosition - 1) sTempString = sTempString & sReplaceWith sTempString = sTempString & _ Mid$(sStringToFix, iPosition + 1, Len(sStringToFix)) iPosition = InStr(iPosition + 1, sStringToFix, sCharToReplace)Loop

SrchReplace = sTempString

End Function

Chapter7/Page276/Globals.basAttribute VB_Name = "Globals"Option Explicit

Public Declare Function sendMessageByString& Lib "user32" _ Alias "SendMessageA" (ByVal hwnd As Long, _ ByVal wMsg As Long, ByVal wParam As Long, _ ByVal lParam As String)

Public Const LB_SELECTSTRING = &H18CPublic gFindString As StringPublic Const gDataBaseName = "C:\BegDB\Biblio.mdb"

Public Sub highLight()

With Screen.ActiveForm If (TypeOf .ActiveControl Is TextBox) Then .ActiveControl.SelStart = 0 .ActiveControl.SelLength = Len(.ActiveControl) End IfEnd With

End Sub

Chapter7/Page276/prjDataControl.exe

Chapter7/Page276/prjDataControl.vbpType=ExeReference=*\G{00020430-0000-0000-C000-000000000046}#2.0#0#..\..\..\..\..\..\..\..\WINNT\System32\stdole2.tlb#OLE AutomationReference=*\G{00025E01-0000-0000-C000-000000000046}#4.0#0#..\..\..\..\..\..\..\..\Program Files\Common Files\Microsoft Shared\DAO\DAO350.DLL#Microsoft DAO 3.51 Object LibraryObject={831FDD16-0C5C-11D2-A9FC-0000F8754DA1}#2.0#0; MSCOMCTL.OCXModule=Globals; Globals.basForm=frmFind.frmClass=dataClass; dataClass.clsForm=frmDataClass.frmStartup="frmDataClass"HelpFile=""Command32=""Name="prjDataControl"HelpContextID="0"CompatibleMode="0"MajorVer=1MinorVer=0RevisionVer=0AutoIncrementVer=0ServerSupportFiles=0VersionCompanyName="Wrox Press"CompilationType=0OptimizationType=0FavorPentiumPro(tm)=0CodeViewDebugInfo=0NoAliasing=0BoundsCheck=0OverflowCheck=0FlPointCheck=0FDIVCheck=0UnroundedFP=0StartMode=0Unattended=0Retained=0ThreadPerObject=0MaxNumberOfThreads=1

[MS Transaction Server]AutoRefresh=1

Chapter7/Page276/prjDataControl.vbwGlobals = 0, 0, 0, 0, CfrmFind = 0, 0, 0, 0, C, 44, 58, 765, 679, CdataClass = 0, 0, 0, 0, CfrmDataClass = 0, 0, 0, 0, C, 22, 29, 743, 650, C

Chapter6/frmFind.frmVERSION 5.00Begin VB.Form frmFind BorderStyle = 3 'Fixed Dialog Caption = "Find Record" ClientHeight = 5400 ClientLeft = 45 ClientTop = 330 ClientWidth = 4830 LinkTopic = "Form2" MaxButton = 0 'False MinButton = 0 'False ScaleHeight = 5400 ScaleWidth = 4830 ShowInTaskbar = 0 'False StartUpPosition = 3 'Windows Default Begin VB.Timer Timer1 Left = 3360 Top = 720 End Begin VB.Data dtaFind Caption = "Data1" Connect = "Access" DatabaseName = "" DefaultCursorType= 0 'DefaultCursor DefaultType = 2 'UseODBC Exclusive = 0 'False Height = 300 Left = 3240 Options = 0 ReadOnly = 0 'False RecordsetType = 1 'Dynaset RecordSource = "" Top = 4440 Visible = 0 'False Width = 1215 End Begin VB.CommandButton cmdCancel Caption = "&Cancel" Height = 495 Left = 1800 TabIndex = 5 Top = 4440 Width = 1215 End Begin VB.ListBox List1 Height = 2205 Left = 360 TabIndex = 3 Top = 1200 W