Upload
douglas-woods
View
213
Download
0
Tags:
Embed Size (px)
Citation preview
McGraw-Hill/Irwin
Programming in Visual Basic 6.0
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Update Edition
Chapter 12
Advanced Data Handling - Grids, Validation, Selection, and Sorting
Programming in Visual Basic 6.0 Update Edition
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
2
McGraw-Hill/Irwin
DataGrids - Microsoft DataGrid Control 6.0 (dbg prefix)DataGrids - Microsoft DataGrid Control 6.0 (dbg prefix)
• Presents the table data in rows and columns like a spreadsheet or datasheet view in Access
• In order to use the datagrid with ADO, you must first add the Microsoft ADO Data Control 6.0 (adodc) to the toolbox– Project, Components, Microsoft ADO Data
Control 6.0
• Then add the datagrid itself to the toolbox– Project, Components, Microsoft DataGrid
Control 6.0
Programming in Visual Basic 6.0 Update Edition
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
3
McGraw-Hill/Irwin
DataGrids - Microsoft DataGrid Control 6.0 (dbg prefix)cont.DataGrids - Microsoft DataGrid Control 6.0 (dbg prefix)cont.
• Draw the ADODC on your form
• Set the properties of the ADODC to point to the database– Name, ConnectionString, CommandType, RecordSource
• Draw the DataGrid on your form
• Link the DataGrid to the ADODC using the DataSource property
• Right Click the DataGrid, Retrieve Fields
• To modify, Right Click, Edit, then select columns for deletion or resize columns
Programming in Visual Basic 6.0 Update Edition
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
4
McGraw-Hill/Irwin
Accessing DataGrid PropertiesAccessing DataGrid Properties
• Some properties are available in the Properties window
• More properties are available from the Property Pages– Properties Window, Custom– OR, Right Click the DataGrid and select
Properties
Programming in Visual Basic 6.0 Update Edition
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
5
McGraw-Hill/Irwin
DataGrid - Property Pages PropertiesDataGrid - Property Pages Properties
• AllowAddNew– Allow user to add new database records from
the grid
• AllowDelete– Allow user to delete database records from the
grid
• Row height
• Column width
Programming in Visual Basic 6.0 Update Edition
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
6
McGraw-Hill/Irwin
Record Count and Record NumberRecord Count and Record Number
• RecordCount property of the recordset holds the number of records in the recordset
• AbsolutePosition property of the recordset hold the position of the current record in the recordset– AbsolutePosition=0 at BOF and EOF
intRecordCount=adoBooks.Recordset.RecordCountintCurrentRecord=adoBooks.Recordset.AbsolutePosition
Programming in Visual Basic 6.0 Update Edition
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
7
McGraw-Hill/Irwin
Displaying Record InfoDisplaying Record Info
• Some programmers display the record info in the Caption of the ADODC
• To display the record number as the user moves from record to record use the ADODC's MoveComplete event which occurs each time a new record becomes current
Programming in Visual Basic 6.0 Update Edition
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
8
McGraw-Hill/Irwin
Displaying Record Info -SetRecordNumber SubprocedureDisplaying Record Info -SetRecordNumber Subprocedure
Private Sub SetRecordNumber( )Dim intCurrentRecord as IntegerDim intRecordCount as IntegerWith adoBooks.Recordset
intCurrentRecord = .AbsolutePositionintRecordCount = .RecordCount
End WithIf adoBooks.Recordset.EOF Then
adoBooks.Caption = "EOF"Else
adoBooks.Caption="Record " & intCurrentRecord & _
" of " & intRecordCountEnd IF
End Sub
Programming in Visual Basic 6.0 Update Edition
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
9
McGraw-Hill/Irwin
MoveComplete Event -Calling SetRecordNumberMoveComplete Event -Calling SetRecordNumber
Private Sub adoBooks_MoveComplete(ByVal adReason As _ADODB.EventReasonEnum, _ByVal pError as ADODB.Error, _adStatus as ADODB.EventStatusEnum, _ ByVal pRecordset as ADODB.Recordset)
SetRecordNumber
End Sub
Programming in Visual Basic 6.0 Update Edition
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
10
McGraw-Hill/Irwin
Preventing User ErrorsPreventing User Errors
• Set TextBox's MaxLength equal to database field length
• Use TextBox's Lock property when you don't want the user to change data, like primary key when not adding a record
• Validate user data BEFORE updating the database
Programming in Visual Basic 6.0 Update Edition
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
11
McGraw-Hill/Irwin
Validating Data-Validate EventValidating Data-Validate Event
• Use Validate event to perform data validation• CausesValidation property=True will invoke
the Validate event just before the control loses focus (default is True!)
• Always set CausesValidation to False for Cancel command button to allow the user "a way out"
Programming in Visual Basic 6.0 Update Edition
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
12
McGraw-Hill/Irwin
Validate Event ExampleValidate Event Example
Private Sub txtEmpID_Validate(Cancel as Boolean)If Not IsNumeric(txtEmpID) Then
MsgBox "Employee Id must be numeric", vbOKOnly,"Invalid Emp ID"
With txtEmpID.SelStart = 0.SelLength = Len(.Text)
End WithCancel =True 'resets focus to txtEmpID
End IfEnd Sub
Programming in Visual Basic 6.0 Update Edition
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
13
McGraw-Hill/Irwin
Trapping Errors with On ErrorTrapping Errors with On Error
• Include error handling for every subprocedure that accesses the database
• Open
• Add
• Delete
• Update
• Move
• Trap errors and inform user
Programming in Visual Basic 6.0 Update Edition
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
14
McGraw-Hill/Irwin
Handling Errors on MovesHandling Errors on Moves
• Code On Error Resume Next to ignore the error and continue execution
Private Sub cmdFirst_Click( )On Error Resume NextadoBooks.Recordset.MoveFirst
End Sub
Programming in Visual Basic 6.0 Update Edition
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
15
McGraw-Hill/Irwin
Handling Errors On DeleteHandling Errors On Delete
• Notify user using MsgBox
• Code On Error GoTo 0 to turn off error trapping and return control to the user
Programming in Visual Basic 6.0 Update Edition
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
16
McGraw-Hill/Irwin
Handling Errors On Delete ExampleHandling Errors On Delete Example
Private Sub cmdDelete_Click( )On Error GoTo ErrorHandlerWith adoBooks.Recordset
.Delete
.MoveNext
. . . see P496 for complete code
ErrorHandler:Dim strMsg as StringstrMsg="Cannot delete record." & vbCrLf & Err.DescriptionMsgBox strMsg, vbExclamation, "Database Error"On Error GoTo 0
End Sub
Programming in Visual Basic 6.0 Update Edition
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
17
McGraw-Hill/Irwin
Handling Errors on AddHandling Errors on Add
• Depending on the thoroughness of your data validation in the Validate event various errors can be generated during Add
• Most common error is duplicate, invalid, or missing primary key
• Error handling code will vary depending on what you want to do as a programmer– Give the user another chance to correctly enter data
– Abort add
Programming in Visual Basic 6.0 Update Edition
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
18
McGraw-Hill/Irwin
Handling Errors on Add ExampleHandling Errors on Add Example
• Review textbook example– Pages 496 - 497– Error: primary key error, ISBN field– Error Handling: allows the user to try again to
enter a valid primary key
Programming in Visual Basic 6.0 Update Edition
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
19
McGraw-Hill/Irwin
Searching for RecordsSearching for Records
• Find Method– Returns single record matching specified criteria
• Filter Property– Returns a subset a records that match the specified
criteria
Programming in Visual Basic 6.0 Update Edition
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
20
McGraw-Hill/Irwin
Find Method SyntaxFind Method Syntax
adoDatControl.Recordset. Find Criteria[, [RowsToSkip], [SearchDirection] ]
• Criteria: String to specify what to search for
• RowsToSkip: Optional, specify number of rows/records to skip from current record before starting to search
• SearchDirection: Optional
– adSearchForward (default)
– adSearchBackward
Programming in Visual Basic 6.0 Update Edition
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
21
McGraw-Hill/Irwin
Find Method ExamplesFind Method Examples
adoMembers.Recordset.Find " Amount > 100"
adoMembers.Recordset.Find " Amount > " & txtAmt.Text
Dim strCriteria as String
strCriteria = "[Last Name] = 'Weldon' "adoPatient.Recordset.Find strCriteria
Important Rules:1. Strings must be enclosed in double quotes, strings inside
strings must be enclosed in single quotes2. Database field names that contain spaces must be
enclosed in square brackets
Programming in Visual Basic 6.0 Update Edition
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
22
McGraw-Hill/Irwin
Search String ExamplesSearch String Examples
• Field name does not contain spaces– "Sex = ' M ' "
• If field name contains spaces add square brackets– "[First Name] = ' Smith ' "
• If data searched for is numeric single quotes are omitted– " Age < 21"
Programming in Visual Basic 6.0 Update Edition
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
23
McGraw-Hill/Irwin
More Search String ExamplesMore Search String Examples
• If data searched for is in a textbox– "[Patient Number] = ' " & txtPatNum.Text & " ' "
• If data searched for is a date use # symbols– " Birthdate > # 1/1/1980 # "
• Wild Cards– "[Last Name] Like ' S* ' "
Programming in Visual Basic 6.0 Update Edition
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
24
McGraw-Hill/Irwin
Preparing for "No Record Found"Preparing for "No Record Found"
• Set a Bookmark before beginning Find so you can return to the record which was current before the find if no record found
• If no record is found the recordset will be at EOF
• Always test for EOF after Find method
Programming in Visual Basic 6.0 Update Edition
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
25
McGraw-Hill/Irwin
BookmarksBookmarks
• Store in variable of variant data type (prefix vnt)• Store before Find method in the variable by using
the Recordset's Bookmark property to save the current record
• If no record found, set the Recordset's Bookmark property equal to the previously stored variable
Programming in Visual Basic 6.0 Update Edition
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
26
McGraw-Hill/Irwin
Find with Bookmark ExampleFind with Bookmark Example
Private Sub cmdFind_Click( )Dim strCriteria as StringDim vntCurrentRecord as VariantIf txtLastName < > "" Then strCriteria="[Last Name] = ' " & txtLastName & " ' " With adoPatient.Recordset
vntCurrentRecord=.Bookmark.MoveFirst.FindNext strCriteriaIf .NoMacth=True Then MsgBox "Record Not Found", vbInformation, "Find" .Bookmark=vntCurrentRecordEnd If
End WithElse MsgBox "Enter a name to be found" txtLastName.SetFocusEnd Sub
Programming in Visual Basic 6.0 Update Edition
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
27
McGraw-Hill/Irwin
Filter PropertyFilter Property
• Creates a new temporary recordset by selecting all records than match the specified criteria
• No changes are made to the underlying table
Programming in Visual Basic 6.0 Update Edition
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
28
McGraw-Hill/Irwin
Filter Property SyntaxFilter Property Syntax
Object.Recordset.Filter = Criteria
• Criteria: String to specify what to search for
• Use the same rules for constructing the criteria string as shown on previous slide for Find method
Programming in Visual Basic 6.0 Update Edition
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
29
McGraw-Hill/Irwin
Removing the FilterRemoving the Filter
• Remove the filter to display entire recordset
• Set Filter property to adFilterNone– adoBooks.Recordset.Filter=adFilterNone
Programming in Visual Basic 6.0 Update Edition
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
30
McGraw-Hill/Irwin
Sort PropertySort Property
• You can sort a recordset by any field using the recordset's Sort property
• You can sort by multiple fields by separating them with commas
• Create a menu or a listbox for user to select field(s) to sort by
• To return recordset's default sort order usually sort by the primary key
Programming in Visual Basic 6.0 Update Edition
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
31
McGraw-Hill/Irwin
Sort Property Syntax & ExamplesSort Property Syntax & Examples
adoBooks.Recordset.Sort = "Author"
adoBooks.Recordset.Sort = "Author, Title"
adoBooks.Recordset.Sort = "ISBN"
Programming in Visual Basic 6.0 Update Edition
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
32
McGraw-Hill/Irwin
Working with Database FieldsWorking with Database Fields
• If your controls ever need to appear empty you can write code to work directly with the database fields
• If user needs to pick from a list of values and based on user's selection other controls are automatically populated
• Gives you more programmatic control
Programming in Visual Basic 6.0 Update Edition
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
33
McGraw-Hill/Irwin
The exclamation point is called the BANG operator.
Referring to Database FieldsReferring to Database Fields
• All these are equivalent:
Field Names containing spaces -adoAVB.Recordset![Last Name]adoAVB.Recordset!("Last Name")adoAVB.Recordset!"Last Name"
Field Names without spaces -adoAVB.Recordset!InsuranceadoAVB.Recordset!("Insurance")
Programming in Visual Basic 6.0 Update Edition
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
34
McGraw-Hill/Irwin
The exclamation point is called the BANG operator.
Code ExamplesCode Examples
• Populating a form's textbox control
txtLName=adoAVB.Recordset![Last Name]
• Writing to the database field from a form's textbox control
adoAVB.Recordset![Last Name]=txtLName
Programming in Visual Basic 6.0 Update Edition
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
35
McGraw-Hill/Irwin
Populating a Combo or List (p508)Populating a Combo or List (p508)
• Use Do Until .EOF for the Recordset during Form_Load or Form_Activate
Private Sub Form_Load ( ) With adoAVB .Recordset
Do Until .EOF If !Lname <> " " Then
cboLName.AddItem !LName End If .MoveNextLoop.Close
End WithEnd Sub
Programming in Visual Basic 6.0 Update Edition
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
36
McGraw-Hill/Irwin
Data Environment DesignerData Environment Designer
• Not available in the Working Model-new in VB 6
• Must be added - Project, Add Data Environment
• Visual Interface that allows programmers to set up all the database connections and recordsets in one location
• After the connections and recordsets are setup, the programmer can simply drag objects from the DE designer to a form to generate data bound-controls automatically
Programming in Visual Basic 6.0 Update Edition
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
37
McGraw-Hill/Irwin
Data Environment (de prefix)Data Environment (de prefix)
• The Data Environment has a hierarchical interface– The Data Environment is at the top of the
hierarchy, used instead of the ADO control– The Data Environment is made up of Connections,
used instead of the ConnectionString of the ADO control
– Connections are made up of Commands, used instead of the RecordSource
– Commands are made up of Fields
Programming in Visual Basic 6.0 Update Edition
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
38
McGraw-Hill/Irwin
Data Environment - graphicallyData Environment - graphically
deAdvancedVision
PatientNumber
conAVB
Patient
LastName
StreetFirstName
DataEnvironment(like ADODC)
DEConnection(like ConnectionString)
DECommand(like RecordSource)
Fields
Programming in Visual Basic 6.0 Update Edition
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
39
McGraw-Hill/Irwin
Steps For Using DE, 1 of 5Steps For Using DE, 1 of 5
• Several possible methods for adding DE, use one– Project Menu, Add Data Environment– Project, Add ActiveX Designers, Data
Environment– Project, Components, Designers tab, Data
Environment
Programming in Visual Basic 6.0 Update Edition
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
40
McGraw-Hill/Irwin
Steps For Using DE, 2 of 5 (cont.)Steps For Using DE, 2 of 5 (cont.)
• Once the DE has been added, the DE window appears
• Rename DE by clicking• Rename Connection by clicking• Set Connection properties by right clicking
to access properties window– Data Link Properties
• Provider• Connection
Programming in Visual Basic 6.0 Update Edition
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
41
McGraw-Hill/Irwin
Steps For Using DE, 3 of 5 (cont.)Steps For Using DE, 3 of 5 (cont.)
• Add Command object by right clicking Connection
• Rename Command by clicking
• Set Command properties by right clicking to access properties window– CommandType ==> adCmdTable– CommandText ==> actual table name
Programming in Visual Basic 6.0 Update Edition
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
42
McGraw-Hill/Irwin
Steps For Using DE, 4 of 5 (cont.)Steps For Using DE, 4 of 5 (cont.)
• Add Command object by right clicking Connection
• Rename Command by clicking
• Set Command properties by right clicking to access properties window– CommandType ==> adCmdTable– CommandText ==> actual table name
Programming in Visual Basic 6.0 Update Edition
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
43
McGraw-Hill/Irwin
Steps For Using DE, 5 of 5 (cont.)Steps For Using DE, 5 of 5 (cont.)
• View list of fields in table by clicking plus symbol beside command object
• If necessary, resize/move DE window so that you can see both the DE window and form
• Create bound controls on form by dragging fields from DE to form
Programming in Visual Basic 6.0 Update Edition
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
44
McGraw-Hill/Irwin
Recordset ObjectRecordset Object
• When using the DE Designer the Command object automatically creates a Recordset object named as follows:– Prefix of "rs" + Command object's name
– Ex: Command object name=Patient, Recordset name used in code is rsPatient
• Reference in code:– deAVB.rsPatient.property or method
– Example: deAVB.rsPatient.MoveNext
Programming in Visual Basic 6.0 Update Edition
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
45
McGraw-Hill/Irwin
Simple Code Comparison: ADODC and DESimple Code Comparison: ADODC and DE
• ADODC:adoPatient.RecordSet.MoveNext
• DE:deAdvancedVision.rsPatient.MoveNext
Programming in Visual Basic 6.0 Update Edition
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
46
McGraw-Hill/Irwin
Open a Database (DE)Open a Database (DE)
• VB automatically handles the opening of a database using the Data Environment Designer
• VB uses the hard-coded connection string of the DE's Connection Object
• Your VB Project is not portable unless you remove the hard-coded connection string and add code using App.Path to create the connection string, just like ADODC
Programming in Visual Basic 6.0 Update Edition
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
47
McGraw-Hill/Irwin
Using App.Path with DE to Open the DatabaseUsing App.Path with DE to Open the Database
• Use DE's Initialize event (rather than Form_Load event as with ADODC)
– Initialize Event fires before any connections are made
– Code the Connection object's ConnectionString (before we coded the ADODC's ConnectionString)
Private Sub DataEnvironment_Initialize( )
conAVB.ConnectionString="Provider=Microsoft.Jet.OLEDB.3.51;" & _
"Persist Security Info=False;" & _
"Data Source=" & App.Path & "\AVB.mdb"
End Sub
Programming in Visual Basic 6.0 Update Edition
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
48
McGraw-Hill/Irwin
conAVB.Close
Close a Database (DE)Close a Database (DE)
• Use the Close method of the DE's Connection object to close a database
• Place this code in the Data Environment's Terminate event (rather than in a form's Unload event as with ADODC)
Programming in Visual Basic 6.0 Update Edition
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
49
McGraw-Hill/Irwin
Private Sub DataEnvironment_Terminate( )
conAVB.Close
End Sub
Closing the Database ExampleClosing the Database Example
• Use DE's Terminate event (rather than Form_Unload event as with ADODC)
Programming in Visual Basic 6.0 Update Edition
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
50
McGraw-Hill/Irwin
One-to-Many Relationships, Data Hierarchies (Pages 518-522)One-to-Many Relationships, Data Hierarchies (Pages 518-522)
• Use the DE Designer to create hierarchies of data• Similar to relationships that join tables• Data hierarchies are useful for displaying
One-to-Many (1-M) relationships• Use MSHFlexGrid control to display the
hierarchies created in the DE Designer – Project, Components, Microsoft Hierarchical FlexGrid
Control 6.0 (OLE DB)
Programming in Visual Basic 6.0 Update Edition
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
51
McGraw-Hill/Irwin
Creating a Relation HierarchyCreating a Relation Hierarchy
• Create DE as described previously• Add the Command objects for
– Parent table (One side of 1-M)
– Child table (Many side of 1-M)
• Right click Child table to access Properties– Relation tab
• Check Relate to a Parent Command Object
• Select parent table's command object
• For Relation Definition, select fields in each table upon which the relationship can be established
• Click Add command button
Programming in Visual Basic 6.0 Update Edition
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
52
McGraw-Hill/Irwin
Displaying the RelationDisplaying the Relation
• Drag the Parent Command Object's fields to the top of the form
• Add the MSHFlexGrid– Project, Components, Microsoft Hierarchical FlexGrid
Control 6.0 (OLE DB)
• Set the properties of the MSHFlexGrid to display the Child Command Object's fields