week
DESCRIPTION
Week. Files, Printing, and Structures. 10. Introduction. Saving data to sequential text files Reading the data back into an application Using the OpenFileDialog, SaveFileDialog, ColorDialog, and FontDialog controls Using the PrintDocument control to print reports from your application - PowerPoint PPT PresentationTRANSCRIPT
Week
Files, Printing, and Structures10
2
Introduction
Saving data to sequential text files Reading the data back into an application Using the OpenFileDialog, SaveFileDialog,
ColorDialog, and FontDialog controls Using the PrintDocument control to print reports
from your application Packaging units of data together into structures
Using Files
A File Is a Collection of Data Stored on a Computer Disk
Information Can Be Saved to Files and Later Reused
4
The Life Span of Data
Thus far, all of our data has been stored in controls and variables existing in RAM
This data disappears once the program stops running
If data is stored in a file on a computer disk, it can be retrieved and used at a later time
5
Three Steps in Using a File
1. The file must be opened
If it does not yet exist, it will be created
2. Data is read from or written to the file
3. The program closes the file
6
Reading and Writing to a File Data must be retrieved from disk and put in
memory for an application to work with it Data is transferred from disk to memory by:
Reading it from an input file Placing it in variables or control properties
Data is transferred from memory to disk by: Writing it to an output file Getting it from variables or control properties
Data is frequently placed in the text property of a control
7
File Types/Access Methods Text file type
Character based text Contents can be viewed by Notepad
Binary file type Pure binary form Contents cannot be viewed with a text editor
Access Methods Sequential access – a continuous stream of data written
and read as a whole from beginning to end Random access – access in any order with data written
to or read from specific places in the file Like the difference between a casette tape and a CD
8
Creating Files with StreamWriter Objects Add Imports System.IO before class declared
Makes StreamWriter classes available in code A StreamWriter object is used to create a
sequential text file in the following way: Declare an object variable of type StreamWriter
Call CreateText method passing the filename
Method returns a StreamWriter object Object is assigned to a StreamWriter variable
Variable phoneFile now defines a stream of data that can be written to phonelist.txt
Dim phoneFile As StreamWriter
phoneFile = File.CreateText(“phonelist.txt”)
9
Appending Text with StreamWriter A StreamWriter object is used to append data to a
sequential text file in the following way: Declare an object variable of type StreamWriter
Call AppendText method passing the filename
Method returns a StreamWriter object Object is assigned to a StreamWriter variable
Variable phoneFile now defines a stream of data that can be added to the end of phonelist.txt
Dim phoneFile As StreamWriter
phoneFile = File.AppendText(“phonelist.txt”)
10
File Paths Filename can include the file path
Can be a complete file path with drive letter“C:\WordProc\memo.txt"
Refer to a file in the default drive root directory"\pricelist.txt"
Or include no path information at all"mytext.txt“
If no path information specified, the bin folder of the current project is used
11
Writing Data to a File
The WriteLine method of a StreamWriter object actually writes data to the file
ObjectVar.WriteLine(Data) Streamwriter object identified by ObjectVar The method’s Data argument consists of
constants or variables with data to be written WriteLine appends an invisible newline character
to the end of the data Omit argument to write a blank line to a file
ObjectVar.WriteLine()
12
Writing Data to a File Example
Dim studentFile As StreamWriterstudentFile = File.CreateText("StudentData.txt")studentFile.WriteLine("Jim")studentFile.WriteLine(95)studentFile.WriteLine("Karen")studentFile.WriteLine(98)studentFile.WriteLine("Bob")studentFile.WriteLine(82)studentFile.Close()
Jim95Karen98Bob82
TheResultingFile,StudentData.txt
13
The StreamWriter Write Method
The Write method writes an item of data without writing a newline character
Usually need to provide some sort of delineation or delimiter between data items A blank space could be used Comma is a more common delimiter
ObjectVar.Write(Data)
14
Closing a StreamWriter Object
Should close files when finished with them Avoids losing data Data is initially written to a buffer Writes unsaved data from the buffer to the file
The Close method of a StreamWriter object clears the buffer and closes the file
ObjectVar.Close() Streamwriter object identified by ObjectVar
15
Appending to a File
If opening an existing file with CreateText Existing contents are removed New text overwrites the old text
If opening an existing file with AppendText Existing contents are retained New text adds on to the end of the old text
If adding a new friend to friendFile, use:
friendFile = File.AppendText("MyFriends.txt")
16
Appending a File Example
‘Declare an object variableDim friendFile as StreamWriter‘Open the filefriendFile = File.AppendText(“MyFriends.txt”)‘Write the datafriendFile.WriteLine(“Bill Johnson”)friendFile.WriteLine(30)friendFile.WriteLine(“36 Oak Street”)‘Close the filefriendFile.Close()
friendFile“After”
Jim Weaver30P.O. Box 124Mary Duncan2447 Elm StreetKaren Warren2824 Love Lane
friendFile “Before”
Jim Weaver30P.O. Box 124Mary Duncan2447 Elm StreetKaren Warren2824 Love LaneBill Johnson3036 Oak Street
17
StreamReader Objects Use StreamReader objects to read from a file Define and open similar to StreamWriter:
Sample code:
Variable phoneFile now defines a stream of data that can be read from phonelist.txt
Must have Imports System.IO before class declaration as was done with StreamWriter
Dim ObjectVar As StreamReaderObjectVar = File.OpenText(Filename)
Dim phoneFile As StreamReaderphoneFile = File.OpenText(“phonelist.txt")
18
Reading Data from a File The ReadLine method of a StreamReader object
actually reads data from the filedataVar = ObjectVar.ReadLine()
Streamreader object identified by ObjectVar The result of the method, the data read from
the file, is assigned to string variable dataVar Sample code:
Dim custFile As StreamReadercustFile = File.OpenText("customer.txt")custName = custFile.ReadLine()
custName holds the data read from the file StreamReader also has a Close method
19
Determining Whether a File Exists The File.OpenText method issues a runtime
error if the file does not exist Avoid this by using the File.Exists method
Format is File.Exists(filename) Returns a boolean result that can be tested:If System.IO.File.Exists(filename) Then
' Open the file.inputFile = System.IO.File.OpenText(filename)
ElseMessageBox.Show(filename & " does not exist.")
End If
20
Detecting the End of a File The Peek method tests if you’ve reached end of
file (no more characters to read) Format is objectvar.Peek If no more characters, the value -1 is returned
Dim scoresFile As StreamReaderDim strInput As StringscoresFile = File.OpenText("Scores.txt")Do Until scoresFile.Peek = -1
strInput = scoresFile.ReadLine()lstResults.Items.Add(strinput)
LoopscoresFile.Close()
21
Read Method Read method returns the integer code of the next
character in the file Chr function converts integer code to character
This loop appends one character at a time to input until no more characters are in the file
Dim textFile As StreamReaderDim strInput As String = String.EmptytextFile = File.OpenText("names.txt")Do While textFile.Peek <> -1
strInput &= Chr(textFile.Read)LooptextFile.Close()
22
ReadToEnd Method ReadToEnd method returns the rest of the file
from the current read position to end of file Functions differently from ReadLine method
ReadToEnd method ignores line delimiters The statement
input = textFile.ReadToEnd reads the file contents and stores it in strInput
Dim textFile As StreamReaderDim strInput As StringtextFile = File.OpenText("names.txt")strInput = textFile.ReadToEndtextFile.Close()
23
Write Then Read an Entire ArrayDim intValues(9)------------------------------------------------Dim outputFile as StreamWriteroutputFile = File.CreateText("values.txt")For intCount = 0 To (intValues.Length – 1)
outputFile.WriteLine(intValues(intCount))Next intCountoutputFile.Close()------------------------------------------------Dim inputFile as StreamReaderinputFile = File.OpenText("values.txt")For intCount = 0 To (intValues.Length – 1)
intValues(intCount) = CInt(inputFile.ReadLine)Next intCountinputFile.Close()
The OpenFileDialog,SaveFileDialog, FontDialog,and ColorDialog Controls
Visual Basic Provides Dialog Controls That Equip Your Applications With Standard Windows Dialog
Boxes for Operations Such As Opening Files, Saving Files, and Selecting Fonts and Colors
25
OpenFileDialog and SaveFileDialog Windows has a standard method of allowing a
user to choose a file to open or save These methods let users browse for a file
The OpenFileDialog and SaveFileDialog controls provide this capability in VB
To use the OpenFileDialog control Double click on this tool in the Toolbox Appears in component tray Use ofd as standard prefix when naming
SaveFileDialog is used in a similar way
26
Displaying an Open Dialog Box Display control with the ShowDialog method
ControlName.ShowDialog() Method returns a value indicating which dialog
box button the user selects, either DialogResult.OK, or DialogResult.Cancel
For example:If ofdOpenfile.Showdialog() = DialogResult.OK Then
MessageBox.Show(ofdOpenFile.FileName)Else
MessageBox.Show(“You selected no file”)End If
27
Dialog Box Filter Property
FileDialog controls have a Filter property Limits files shown to specific file extensions Specify filter description shown to user first Then specify the filter itself Pipe symbol (|) used as a delimiter
Following Filter property lets user choose: Text files (*.txt), displays all .txt files All files (*.*), displays all file extensions
ofdOpenFile.Filter = "Text files (*.txt)|*.txt|" & _ "All files (*.*)|*.*"
28
Other OpenFileDialog Properties InitialDirectory property specifies folder to use
Default if not specified is current folder To set dialog box initial directory to C:\Data:
ofdOpenFile.InitialDirectory = “C:\Data”
Title property specifies the text on the title bar Default title is Open if not specified
ofdOpenFile.Title = “Select a File to Open”
Filename property returns file selected from dialog box by user, in this case to selectedFile
selectedFile = ofdOpenFile.Filename
29
Open Dialog Box Example
' Configure the Open dialog box and display it.With ofdOpenFile
.Filter = "Text files (*.txt)|*.txt|" & _"All files (*.*)|*.*"
.InitialDirectory = "C:\Data"
.Title = "Select a File to Open"If .ShowDialog() = DialogResult.OK Then
inputFile = System.IO.File.OpenText(.Filename)End If
End With
User may choose to display .txt files or all files Files from Data folder of hard drive are shown Dialog box title shows Select a File to Open Variable inputFile holds file selected by user
30
Open Dialog Box Example InitialDirectory property Title property Filter property
31
SaveFileDialog Control SaveFileDialog uses the same methods:
ShowDialog() The same properties:
Filter InitialDirectory Title Filename
And the same result constants: DialogResult.OK DialogResult.Cancel
The PrintDocument Control
The PrintDocument Control Allows You to Print Data to the Printer
33
PrintDocument Control
Allows you to send output to the printer To use the PrintDocument control
Double click the tool in the Toolbox Appears in component tray Use pd as standard prefix when naming
PrintDocument control has a Print method This method starts the printing process Format is:
PrintDocumentControl.Print() This triggers a PrintPage event
34
PrintPage Event Handler
Private Sub pdPrint_PrintPage(ByVal sender As System.Object, _ByVal e As System.Drawing.Printing.PrintPageEventArgs) _Handles pdPrint.PrintPage
‘Your print code inserted here
End Sub
The code in the PrintPage event handler performs the actual printing Double click PrintDocument control in tray This creates the PrintPage event handler Insert your print code inside the event handler Basic format of event handler shown below:
35
DrawString Method
The DrawString method is used inside the PrintPage event to: Specify data to send to the printer in string Set font, font size, and font style Determine horizontal position (HPos) of text Determine vertical position (VPos) of text Brushes.Black specifies output in black
DrawString method is formatted as follows:e.Graphics.DrawString(String, _
New Font(FontName, Size, Style), _Brushes.Black, HPos, VPos)
36
Specifying Fonts, Sizes, Styles
Fonts are specified with the string which names the font to be used "Times New Roman" “Arial" , etc.
Sizes are specified with a number 10, 12, etc.
Print effects are specified with provided constants FontStyle.Regular FontStyle.Bold FontStyle.Underline
37
Sample PrintPage Event Procedure
Private Sub pdPrint_PrintPage(ByVal sender As System.Object, _ByVal e As System.Drawing.Printing.PrintPageEventArgs) _Handles pdPrint.PrintPage
Dim inputFile As StreamReaderDim intX As Integer = 10 ‘Horizontal PositionDim intY As Integer = 10 ‘Vertical Position
inputFile = File.OpenText(strFilename)Do While inputFile.Peek <> -1
e.Graphics.DrawString(inputFile.ReadLine, _New Font("Courier", 10, FontStyle.Regular), _Brushes.Black, intX, intY)
intY += 12 ‘Increment Vert PosLoopinputFile.Close()End Sub
38
Printing Column Based Reports Business reports typically contain a:
Report header printed at the top of the page Report body with the data, usually in columns Optional footer, often totalling certain columns
Report header usually has column headings Monospaced font used for column reports
Each character takes same amount of space This allows columns to be aligned
String.Format used to align data along column boundaries
39
String.Format Example
String.Format("{0, 7}{1, -10}{2, 7}", 50, "Arg1", 6)
Specifiesthe argument
numberSpecifies field width for arg
negative - left justifiedpositive - right justified
Argument 0Argument 1
Argument 2
Results in the following output:
50Arg 1 6
7 spaces 10 spacesLeft Justified
7 spaces
Structures
Visual Basic Allows You to Create Your Own Data Types, in Which You May
Group Multiple Data Fields
41
Structures vs. Arrays
Arrays: Multiple fields in one array All of the same data type Distinguished by a numerical index
Structures Multiple fields in one structure Can be of differing data types Distinguished by a field name
42
Syntax for Declaring a Structure
StructureName is a name that identifies the structure itself
FieldDeclarations are the declarations of the individual fields within the structure
[AccessSpecifier] Structure StructureNameFieldDeclarations
End Structure
43
Structure Declaration Example
Structure EmpPayDataDim intEmpNumber As IntegerDim strFirstName As StringDim strLastName As StringDim sngHours As SingleDim decPayRate As DecimalDim decGrossPay As Decimal
End Structure
Following declares a structure with six fields intended to record employee payroll data
Structure name is EmpPayData
44
Creating and Initializing a Structure
Dim deptHead As EmpPayData
deptHead.strEmpNumber = 1101deptHead.strFirstName = "Joanne"deptHead.strLastName = "Smith"deptHead.sngHours = 40deptHead.decPayRate = 25deptHead.decGrossPay = CDec(deptHead.sngHours) * _
deptHead.decPayRate
Using the EmpPayData structure just defined Define variable deptHead of type EmpPayData deptHead contains the six fields in the structure Access each field using varName.fieldName
45
Passing Structure Variables to Procedures and Functions
Structures can be passed to procedures and functions like any other variable
The data type to use in the specification is the name of the structure
Sub CalcPay(ByRef employee as EmpPaydata)‘ This procedure accepts an EmpPayData variable‘ as its argument. The employee’s gross pay‘ is calculated and stored in the grossPay‘ field.With employee
.decGrossPay = .sngHours * .decPayRateEnd With
End Sub
46
Structures Containing Arrays
Structure StudentRecordDim strName As StringDim sngTestScores() As Single
End Structure
Dim student As StudentRecordReDim student.sngTestScores(4)student.strName = "Mary McBride"student.sngTestScores(0) = 89Student.sngTestScores(1) = 92Student.sngTestScores(2) = 84Student.sngTestScores(3) = 96Student.sngTestScores(4) = 91
Structures can contain arrays Must ReDim after declaring structure variable
47
Can declare an array of structures Example below declares employees as an array
of type EmpPayData with 10 elements Can refer to each field using the format
arrayName(index).fieldName
Arrays Containing Structures
Dim employees(9) As EmpPayData
' Refer to the empNumber of the first employeeemployees(0).empNumber = 1101