Vous êtes sur la page 1sur 69

Programming in Visual Basic 6.

Update Edition
Chapter 10 Data Files

2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

Data Files

Files stored on disk device Contain actual data Records ==> Rows or lines Fields ==> Data elements within row Usually stored in an organized manner
Sorted by one of the fields Key Field, unique data item for each record

2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

Sequential File Organization

Records end with CR, File ends with EOF Fields separated by comma delimiters
Variable length Strings enclosed in quotes Numbers not enclosed in quotes

Read only in the order it was written


To read a field you must read all preceding fields of all preceding records "Start at the beginning and continue to the end"

2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

Sequential File Example

"Lynne","Weldon","999 Wide Way","Aiken","SC","29803" <CR> "Jim","Buck","1 Cow Lane","Aiken","SC","29801" <CR> "Tom","Thumb","PO Box 200","Aiken","SC","29802-200" <EOF>

2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

Random File Organization

Records are fixed length and have a record number for reference Fields are fixed length and position
Less data then length will be padded with spaces More data than length will be truncated

Read or written in any order Think of the structure being "like a table"

2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

Random File Example

Lynne Jim Tom

Weldon Buckner Thumb

803-649-9999 803-652-1111 803-593-1234

2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

Processing Data Files

Open file Read or Write Close file

2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

Open Statement

Usually coded in Form_Load

Open "fully qualified path for filename" For {Input| Output|Append|Random} As #FileNumber [Len=RecLength] { } indicates required - pick one [ ] indicates optional FileNumber = 1 to 511, RecLength Max = 32,767
Tip: Instead of specifying entire path, always store the sequential files in the same directory as your VB Project and use App.Path to specify the path
2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

Open For

Input
reads a previously stored file from disk

Output
writes file to disk beginning at BOF, overwriting previous records

Append
Writes file to disk beginning at existing EOF

Random
Reads or writes random files

2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

10

Open Statement Examples

Sequential
Open "C:\VB6\myfile.txt " For Input As #6 Open "A:\myfile.txt " For Output As #1 Open App.Path & \myfile.txt " For Append As #2

Random
Open "A:\myfile.txt " For Random As #3 Len=60

2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

11

Actions Occurring Upon Open

Directory is checked for file


Does not exist - then create unless opened for input where it must already exist

Buffer in memory established


Len determines buffer size When buffer is full VB writes data to disk

File Pointer is created for current location


Located at BOF for Input, Output, and Random Located at EOF for Append

File Number established


Must be unique while file open

2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

12

Locating a File

Problem: Open statement requires fully qualified path for filename Alternative 1:
Require that all data files be saved in the same directory as the VB project Use App.Path to specify the path as follows, Dim strPath as String strPath=App.Path & "\Filename.extension" Open strPath for Input as #4

Alternative 2:
Use Common Dialog with ShowOpen method to display Open dialog for user to locate file

2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

13

Locating a File-Using Common Dialog Dim strFileName as String With dlgCommon .DialogTitle = "Open" .CancelError = False .Filter = "All Files (*.*)|*.*" .ShowOpen If Len(.FileName) = 0 Then Exit Sub End If strFileName=.FileName End With Open strFileName for Input as #1

2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

14

Close Statement

Terminates processing of a disk file Usually coded in Form_Unload, mnuFileSave, mnuFileSaveAs, mnuFileExit

Close [#FileNumber]
[] indicates optional If FileNumber is omitted then all open files are closed
2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

15

Close Statement Examples

Close #6 Close #1, #3 Close

2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

16

Actions Occurring Upon Close

Physically writes the last partially filled buffer to disk for sequential files (Write statement has placed data in the buffer) Writes EOF Releases the Buffer Releases the FileNumber
Note: END closes all open files but is not the best way to close files. You should close files explicitly!

2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

17

Getting Next Available FileNumber

FreeFile Function System assigns next available number Advantages


Never have FileNumber conflicts Don't have to keep track of FileNumbers

DimintFileNumberasInteger intFileNumber=FreeFile Open"Names.txt"ForOutputAs#intFileNumber


2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0

Update Edition
Sequential Files

2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

19

Reading a Sequential File

Open an existing file for Input Use Input Statement to read the records

2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

20

Input Statement

Usually coded in Form_Load If populating a listbox or combo use a Do Until EOF to read data

Input #FileNumber, List of variables Input #2, strCourseNum, strClass, intHours

2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

21

Input Statement (cont.)

If populating a listbox or combo use a Do Until EOF to read in Form_Load

Dim strVideoTitle as String Do Until EOF(3) Input #3, strVideoTitle cboVideoTitle.AddItem strVideoTitle Loop Noticenumbersmatch!
2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

22

Write Statement

Use to place/save data in a sequential file File must already be opened "For Output" Place code in mnuFileSave, mnuFileClose or Form_QueryUnload Follow with a Close statement

2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

23

Write Statement (cont.)

Example

Write #FileNumber, List of variable or fields Write #1, txtFirstName, txtLastName, txtStreet, txtCity, txtxState, txtPhone Write #2, strCourseNum, strClass, intHours

2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

24

Write Statement (cont.)

If populating a listbox or combo use a For Next structure to write/save data

Dim intIndex as Integer Open "A:\videos.txt" For Output As #1 For intIndex=0 to cboVideoTitle.ListCount-1 Write #1, cboVideoTitle.ListIndex Next intIndex Close #1

2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

25

Deleting a Sequential File

Kill statement File cannot be open when Kill is used

Kill "fully qualified path for filename" Kill "A:\Names.txt"

2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

26

Renaming a Sequential File

Name statement File cannot be open when Name is used

Name "old fully qualified path for filename" As "new fully qualified path for filename" Name "A:\Names.txt" As "A:\People.txt"

2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

27

Updating/Overwriting a Sequential File

By updating we mean "saving changes made"


Open the original file for Input Open a temp file for Output Input a record from the original into text boxes or other controls on a form that the user can change Write out the record to the temp file after the user changes the data Close both files Kill the original file Rename the temp file as the original file

2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

28

Inserting Records At the EOF

Open the file for Append Allow the user to enter new data using textboxes or other controls on a form Write the data once a complete record of data has been entered Close the file after all new records have been inserted

2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

29

Creating a New File

Open the file for Output If the filename does not exist VB will create the file Write data to the file from textboxes or other controls the user enters data into Close the file

2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

30

Saving Changes to a File

Standard practice is to ask the user if they want to save the changes before program termination
Set up a module level Boolean variable to identify if changes have been made In Form_QueryUnload event
Check module level Boolean variable to see if changes have been made If TRUE ask the user if they want to save If user responds "yes", save

Code example p 403


2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0

Update Edition
Trapping Program Errors

2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

32

Error Handling

Trap run-time errors rather than having user deal with them or program terminating Some problems cannot be avoided - BUT they must be anticipated
Drive or printer not functioning Improperly formatted disk File not found

2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

33

Most Common Run-Time Errors

11 13 482 53 61 68 71 75 76

Division by 0 Type mismatch *** Printer error File not found Disk full Device unavailable Disk not ready Path/file access error Path not found

2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

34

When a run-time error occurs

VB generates an error number VB checks the number against a table of known error codes Programmer can intercept the error code and take action before VB terminates the project

2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

35

Error Trapping Steps

Turn on the error-handling feature using On Error statement in subprocedure Create error handling code routines
Set them off from other code with line labels

Write code to continue after the error is "handled"

2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

36

On Error Statement

Use this statement at the beginning of a procedure to activate error trapping Designate a line label in the same procedure to go to if an error occurs
Line labels - begin in column 1, end with colon:

On Error GoTo ErrorHandler

Refers to line label

2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

37

Error Handling Code

Precede with Exit Sub statement (or Exit Function) Check the error number(s)
Single error number -- If structure Multiple error numbers -- Select Case

Inform user if necessary Designate next line of code to execute


Resume Resume Next Resume line label

2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

38

Resume

What line of code should be executed after the error has been handled? Resume - line of code that caused error Resume Next - line of code that would logically be executed after the line of code that caused error Resume line label - line with indicated label

2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

39

Err Object

Intrinsic VB object (like Printer object you used in 1st semester VB class) Properties
Number - error number, 0 to 65,535 Source - object or application that caused error Description

Method
Raise - set an error number and/or cause it to occur

2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

40

Error Handling Standards

Use Resume if you identify the problem and the user could correct it Use Resume Next if you identify the problem and execution can proceed without running the error generating line of code Raise the error again (Err.Raise Err) if you cannot identify the problem so VB will handle it and generate a system error message

2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

41

Error Handling Standards (cont.)

Use Resume line label if you want to exit the procedure Call you exit procedure (perhaps, mnuFileExit) to end without displaying any error message Turn off error handling/trapping with: On Error GoTo 0

2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

42

Handling One Error Number Private Sub Whatever( ) On Error GoTo ErrorHandler code to do whatever this subprocedure does Exit Sub ErrorHandler: If Err.Number=71 msgbox to inform user of error for correction Resume Else Err.Raise Err End If End Sub
2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

43

Handling Multiple Error Numbers Private Sub Whatever( ) On Error GoTo ErrorHandler code to do whatever this subprocedure does Exit Sub ErrorHandler: Select Case Err.Number Case 71 Msgbox Case 53, 76 Msgbox Case Else Err.Raise Err End Select Resume End Sub
2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0

Update Edition
Random Files

2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

45

Random File Organization

Records are fixed length and have a record number (data type=long integer) for reference Fields are fixed length and position
Less data then length will be padded with spaces More data than length will be truncated

Read or written in any order Think of the structure being "like a table"

2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

46

Random File Example

Lynne Jim Tom

Weldon Buckner Thumb

803-649-9999 803-652-1111 803-593-1234

2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

47

Defining the Record Structure

Must be done before reading or writing Use Type/End Type statements Code in General Declarations Use fixed length strings
Specify length in Dim statement Ex: Dim strFName as String * 20

Number variables do not require explicit length

2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

48

Type/End Type

PrivateTypePerson intEmpNum AsInteger strFName AsString*20 strLName AsString*30 strPhone AsString*12 curRate AsCurrency EndType DimmudtPersonRecordAsPerson OpenApp.Path&"\Names.dat"ForRandomas#1 Len=Len(mudtPersonRecord)
Note:mudtprefixforUserDefinedType
2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

49

Open Statement

Once the random file is opened it can be used for both input and output unlike sequential files! If you open a file that does not exist, VB will create it as an empty file Once opened, data are available for read/write operations one record at a time

2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

50

Reading a Random File

Open an existing file for Random Use Get Statement to read the records

2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

51

Get Statement

Usually coded in Form_Load If populating a listbox or combo use a Do Until reach last record to read data

Get #FileNumber, [RecordNumber], RecordName Get #2, 4, mudtPersonRecord Get #2, intRecordNumber, mudtPersonRecord
[]indicatesoptional,ifRecordNumberisomitted,thenextrecordisread
2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

52

Put Statement

Use to place/save data in a random file File must already be opened "For Random" Place code in mnuFileSave, mnuFileClose or Form_QueryUnload Follow with a Close statement

2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

53

Put Statement Example

Put #FileNumber, [RecordNumber], RecordName Put #2, 4, mudtPersonRecord Put #2, intRecordNumber, mudtPersonRecord

[]indicatesoptional,ifRecordNumberisomitted,thenext recordisread
2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

54

Accessing the Fields

Get and Put operate on an entire record Reference the individual fields using dot notation for the User Defined Type

2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

55

Accessing the Fields (cont.)

Read using Get then update textbox


Get #2, 1, mudtPersonRecord txtLName.Text=mudtPersonRecord.strLName

Update field from textbox the Write using Put:


mudtPersonRecord.strPhone=txtPhone.Text Put #2, 1, mudtPersonRecord

2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

56

LOF Function

Length of File function returns the size of the file in bytes Use instead of EOF used for sequential files To determine the highest record number in the file divide LOF by the size of one record

LOF(FileNumber) LOF(3) intNumRecords=LOF(3)/Len(mudtPersonRecord)


2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

57

Seek Function

Returns the current location of the pointer = the next record in the file to be processed

Seek(FileNumber) intNextRecord=Seek(3)

2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

58

Trim Functions

Remove extra blank spaces in a string Trim ==> removes spaces from both ends LTrim==> removes spaces at left end RTrim ==> removes spaces at right end

Trim(String) LTrim(String) RTrim(String)


txtLName.Text=RTrim(mudtPersonRecord.strLName)
2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

59

Reading/Retrieving Records Sample Code

Sub GetRecord(lngRecNum as Long) Get #1, lngRecNum, mudtPersonRecord With mudtPhoneRecord txtEmpNum.Text = .intEmpNum txtFName.Text = RTrim(.strFName) txtLName.Text = Rtrim(.strLName) txtPhone.Text = Rtrim(.strPhone) txtRate.Text = .curRate End With End Sub

2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

60

Writing Records Sample Code

Sub PutRecord(lngRecNum as Long) With mudtPhoneRecord .intEmpNum=Val(txtEmpNum.Text) .strFName = txtFName.Text .strLName = txtLName.Text .strPhone = txtPhone.Text .curRate = Val(txtRate.Text) End With Put #1, lngRecNum, mudtPersonRecord End Sub

2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

61

Using ListBox to Store Random File Key Field (p 413)

When you Get or Put a record you need to know the record number To keep track of record numbers store them in ItemData property of ListBox When user selects a value from the list, read its ItemData property to retrieve the desired record

2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

62

Updating a Random File

Create routines to
Edit existing records Add new records Delete existing records

2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

63

Edit Existing Records

Display the record Disable all command buttons except Save and Cancel Lock text boxes for fields containing data you do not want the user to modify

2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

64

Add New Records

Clear all text boxes on form Disable all command buttons except Save and Cancel When user clicks Save write the new record at the end of the file If using a list box to store record numbers, update listbox by adding new data and record number

2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

65

Delete Existing Records No way to delete a record in place Various methods are used to indicate that a record is to be treated as "deleted"
Write a special character in an existing field to indicate deleted Include a "Delete Code" field in the record description and mark it True to indicate deleted

If using a list box to store record numbers, update listbox by deleting the record's associated data and record number

2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0

Update Edition
Programming Hints

2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

67

InputBox Function

Used to request simple input from user Similar in syntax and usage to the MsgBox function Includes
prompt to inform user of desired input text box for user to enter input OK and Cancel command buttons

2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

68

InputBox Syntax

VariableName = InputBox("Prompt" [, "Title"] [, Default] [, XPos] [, YPos]) Where:


Prompt - displays in the dialog to inform the user of what to input Title - displays in the title bar of the dialog Default - default value than displays in the text box of the dialog XPos - Horizontal position of the top left corner of the dialog YPos - Vertical position of the top left corner of the dialog

2002 The McGraw-Hill Companies, Inc. All rights reserved.

Programming in Visual Basic 6.0 Update Edition

69

InputBox Examples

strName = InputBox ("Enter Your Name") intQuan = InputBox ("How many do you want?", _ "Order Quantity", 1)

2002 The McGraw-Hill Companies, Inc. All rights reserved.

Vous aimerez peut-être aussi