Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 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

2 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) 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

3 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. 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

4 Programming in Visual Basic 6.0 Update Edition © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 4 McGraw-Hill/Irwin Accessing 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

5 Programming in Visual Basic 6.0 Update Edition © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 5 McGraw-Hill/Irwin DataGrid - 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

6 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 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.RecordCount intCurrentRecord=adoBooks.Recordset.AbsolutePosition

7 Programming in Visual Basic 6.0 Update Edition © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 7 McGraw-Hill/Irwin Displaying 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

8 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 Subprocedure Private Sub SetRecordNumber( ) Dim intCurrentRecord as Integer Dim intRecordCount as Integer With adoBooks.Recordset intCurrentRecord =.AbsolutePosition intRecordCount =.RecordCount End With If adoBooks.Recordset.EOF Then adoBooks.Caption = "EOF" Else adoBooks.Caption="Record " & intCurrentRecord & _ " of " & intRecordCount End IF End Sub

9 Programming in Visual Basic 6.0 Update Edition © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 9 McGraw-Hill/Irwin MoveComplete 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

10 Programming in Visual Basic 6.0 Update Edition © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 10 McGraw-Hill/Irwin Preventing 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

11 Programming in Visual Basic 6.0 Update Edition © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 11 McGraw-Hill/Irwin Validating 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"

12 Programming in Visual Basic 6.0 Update Edition © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 12 McGraw-Hill/Irwin Validate 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 With Cancel =True'resets focus to txtEmpID End If End Sub

13 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 Error Include error handling for every subprocedure that accesses the database Open Add Delete Update Move Trap errors and inform user

14 Programming in Visual Basic 6.0 Update Edition © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 14 McGraw-Hill/Irwin Handling Errors on Moves Code On Error Resume Next to ignore the error and continue execution Private Sub cmdFirst_Click( ) On Error Resume Next adoBooks.Recordset.MoveFirst End Sub

15 Programming in Visual Basic 6.0 Update Edition © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 15 McGraw-Hill/Irwin Handling Errors On Delete Notify user using MsgBox Code On Error GoTo 0 to turn off error trapping and return control to the user

16 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 Example Private Sub cmdDelete_Click( ) On Error GoTo ErrorHandler With adoBooks.Recordset.Delete.MoveNext... see P496 for complete code ErrorHandler: Dim strMsg as String strMsg="Cannot delete record." & vbCrLf & Err.Description MsgBox strMsg, vbExclamation, "Database Error" On Error GoTo 0 End Sub

17 Programming in Visual Basic 6.0 Update Edition © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 17 McGraw-Hill/Irwin Handling 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

18 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 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

19 Programming in Visual Basic 6.0 Update Edition © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 19 McGraw-Hill/Irwin Searching for Records Find Method –Returns single record matching specified criteria Filter Property –Returns a subset a records that match the specified criteria

20 Programming in Visual Basic 6.0 Update Edition © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 20 McGraw-Hill/Irwin Find 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

21 Programming in Visual Basic 6.0 Update Edition © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 21 McGraw-Hill/Irwin Find 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 quotes 2.Database field names that contain spaces must be enclosed in square brackets

22 Programming in Visual Basic 6.0 Update Edition © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 22 McGraw-Hill/Irwin Search 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"

23 Programming in Visual Basic 6.0 Update Edition © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 23 McGraw-Hill/Irwin More 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* ' "

24 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" 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

25 Programming in Visual Basic 6.0 Update Edition © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 25 McGraw-Hill/Irwin Bookmarks 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

26 Programming in Visual Basic 6.0 Update Edition © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 26 McGraw-Hill/Irwin Find with Bookmark Example Private Sub cmdFind_Click( ) Dim strCriteria as String Dim vntCurrentRecord as Variant If txtLastName "" Then strCriteria="[Last Name] = ' " & txtLastName & " ' " With adoPatient.Recordset vntCurrentRecord=.Bookmark.MoveFirst.FindNext strCriteria If.NoMacth=True Then MsgBox "Record Not Found", vbInformation, "Find".Bookmark=vntCurrentRecord End If End With Else MsgBox "Enter a name to be found" txtLastName.SetFocus End Sub

27 Programming in Visual Basic 6.0 Update Edition © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 27 McGraw-Hill/Irwin Filter Property Creates a new temporary recordset by selecting all records than match the specified criteria No changes are made to the underlying table

28 Programming in Visual Basic 6.0 Update Edition © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 28 McGraw-Hill/Irwin Filter 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

29 Programming in Visual Basic 6.0 Update Edition © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 29 McGraw-Hill/Irwin Removing the Filter Remove the filter to display entire recordset Set Filter property to adFilterNone –adoBooks.Recordset.Filter=adFilterNone

30 Programming in Visual Basic 6.0 Update Edition © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 30 McGraw-Hill/Irwin Sort 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

31 Programming in Visual Basic 6.0 Update Edition © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 31 McGraw-Hill/Irwin Sort Property Syntax & Examples adoBooks.Recordset.Sort = "Author" adoBooks.Recordset.Sort = "Author, Title" adoBooks.Recordset.Sort = "ISBN"

32 Programming in Visual Basic 6.0 Update Edition © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 32 McGraw-Hill/Irwin Working 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

33 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 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!Insurance adoAVB.Recordset!("Insurance")

34 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 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

35 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) 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.MoveNext Loop.Close End With End Sub

36 Programming in Visual Basic 6.0 Update Edition © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 36 McGraw-Hill/Irwin Data 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

37 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) 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

38 Programming in Visual Basic 6.0 Update Edition © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 38 McGraw-Hill/Irwin Data Environment - graphically deAdvancedVision PatientNumber conAVB Patient LastName Street FirstName DataEnvironment (like ADODC) DEConnection (like ConnectionString) DECommand (like RecordSource) Fields

39 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 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

40 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.) 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

41 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.) 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

42 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.) 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

43 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.) 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

44 Programming in Visual Basic 6.0 Update Edition © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 44 McGraw-Hill/Irwin Recordset 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

45 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 DE ADODC: adoPatient.RecordSet.MoveNext DE: deAdvancedVision.rsPatient.MoveNext

46 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) 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

47 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 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

48 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) 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)

49 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 Example Use DE's Terminate event (rather than Form_Unload event as with ADODC)

50 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) 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)

51 Programming in Visual Basic 6.0 Update Edition © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 51 McGraw-Hill/Irwin Creating 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

52 Programming in Visual Basic 6.0 Update Edition © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 52 McGraw-Hill/Irwin Displaying 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


Download ppt "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."

Similar presentations


Ads by Google