Chapter 9, Slide 1 Starting Out with Visual Basic 3 rd Edition Chapter 9 Files, Printing, and Structures
Mar 27, 2015
Chapter 9, Slide 1 Starting Out with Visual Basic 3rd Edition
Chapter 9
Files, Printing, and Structures
Chapter 9, Slide 2 Starting Out with Visual Basic 3rd Edition
Chapter 9Introduction
Chapter 9, Slide 3 Starting Out with Visual Basic 3rd Edition
Chapter 9 Topics 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
Chapter 9, Slide 4 Starting Out with Visual Basic 3rd Edition
Section 9.1Using Files
A File Is a Collection of Data Stored on a Computer Disk
Information Can Be Saved to Files and Later Reused
Chapter 9, Slide 5 Starting Out with Visual Basic 3rd Edition
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
Chapter 9, Slide 6 Starting Out with Visual Basic 3rd Edition
Three Steps in Using a File
1. The file must be openedIf 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
Chapter 9, Slide 7 Starting Out with Visual Basic 3rd Edition
Reading and Writing to a File
Data must be in 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
Chapter 9, Slide 8 Starting Out with Visual Basic 3rd Edition
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
Chapter 9, Slide 9 Starting Out with Visual Basic 3rd Edition
Establishing StreamWriter Objects A StreamWriter object is used to write to a
sequential text file in the following way:• Declare a variable of type StreamWriter
• Create a StreamWriter object and assign it to the StreamWriter variable using either the
• CreateText method for new files
• AppendText method for existing files
Variable phoneFile now defines a stream of data that can be written to phonelist.txt
Dim phoneFile As System.IO.StreamWriter
phoneFile = System.IO.File.CreateText(“phonelist.txt”)
phoneFile = System.IO.File.AppendText(“phonelist.txt”)
Chapter 9, Slide 10 Starting Out with Visual Basic 3rd Edition
Using a String Variable as File Name Filename can be a string literal as already
shown but a string variable is more flexible• User can select the file they wish to edit• What if Notepad could only edit “textfile.txt”?
Example with string variable as filename
Can allow the user to enter the filename• Substitute txtFile.text for “customer.txt” • User can then enter filename in a text box
Dim custFile As System.IO.StreamWriterDim fileName as StringfileName = “customer.txt”custFile = System.IO.file.AppendText(fileName)
Chapter 9, Slide 11 Starting Out with Visual Basic 3rd Edition
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
Chapter 9, Slide 12 Starting Out with Visual Basic 3rd Edition
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()
Chapter 9, Slide 13 Starting Out with Visual Basic 3rd Edition
Closing a StreamWriter Object
Should close files when finished with them• Avoids losing data• Data is initially written to a buffer• Close writes unsaved data from the buffer to
the file The Close method of a StreamWriter object
clears the buffer and closes the fileObjectVar.Close()
• Streamwriter object identified by ObjectVar
Chapter 9, Slide 14 Starting Out with Visual Basic 3rd Edition
Writing Data to a File Example
Dim studentFile As System.IO.StreamWriterstudentFile = System.IO.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
Tutorial 9-1 is an example of an application that writes data to a file
Chapter 9, Slide 15 Starting Out with Visual Basic 3rd Edition
Importing a Namespace System.IO is referred to as a namespace
• A group of logically related classes• System.IO contains StreamWriter and other
file related classes Can shorten references to such classes by
importing the namespace in your codeImports System.IO
• Allows us to use Dim custFile As StreamWriter
• Instead of Dim custFile As System.IO.StreamWriter
Chapter 9, Slide 16 Starting Out with Visual Basic 3rd Edition
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, you’d use
friendFile = System.IO.File.AppendText("MyFriends.txt")
Chapter 9, Slide 17 Starting Out with Visual Basic 3rd Edition
The StreamWriter Write Method
The Write method does not place a newline character after each data item
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)
Chapter 9, Slide 18 Starting Out with Visual Basic 3rd Edition
Write Method Example
Dim name As String = "Jeffrey Smith"Dim idNum As Integer = 47895Dim phone As String = "555-7864"
outputFile.Write(name)outputFile.Write(" ")outputFile.Write(idNum)outputFile.Write(" ")outputFile.WriteLine(phone)
Jeffrey Smith 47895 555-7864
TheResultingFile
Chapter 9, Slide 19 Starting Out with Visual Basic 3rd Edition
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
Dim ObjectVar As System.IO.StreamReaderObjectVar = System.IO.File.OpenText(Filename)
Dim phoneFile As System.IO.StreamReaderphoneFile = System.IO.File.OpenText(“phonelist.txt")
Chapter 9, Slide 20 Starting Out with Visual Basic 3rd Edition
Reading Data from a File The ReadLine method of a StreamReader
object actually reads data from the filedataVar = ObjectVar.ReadLine()
• Streamwriter 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 System.IO.StreamReadercustFile = System.IO.File.OpenText("customer.txt")custName = custFile.ReadLine()
custName holds the data read from the file StreamReader also has a Close method
Chapter 9, Slide 21 Starting Out with Visual Basic 3rd Edition
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:
Tutorial 9-2 shows how to read text file data
If System.IO.File.Exists(filename) Then' Open the file.inputFile = System.IO.File.OpenText(filename)
ElseMessageBox.Show(filename & " does not exist.")
End If
Chapter 9, Slide 22 Starting Out with Visual Basic 3rd Edition
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
Tutorial 9-3 demonstrates the Peek method
Imports System.IODim scoresFile As StreamReaderDim input As StringscoresFile = File.OpenText("Scores.txt")Do Until scoresFile.Peek = -1
input = scoresFile.ReadLine()lstResults.Items.Add(input)
LoopscoresFile.Close()
Chapter 9, Slide 23 Starting Out with Visual Basic 3rd Edition
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
Imports System.IODim textFile As StreamReaderDim input As StringtextFile = File.OpenText("names.txt")Do While textFile.Peek <> -1
input &= Chr(textFile.Read)LooptextFile.Close()
Chapter 9, Slide 24 Starting Out with Visual Basic 3rd Edition
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 input
Imports System.IODim textFile As StreamReaderDim input As StringtextFile = File.OpenText("names.txt")input = textFile.ReadToEndtextFile.Close()
Chapter 9, Slide 25 Starting Out with Visual Basic 3rd Edition
Write Then Read an Entire Array
Imports System.IODim intValues(9)------------------------------------------------Dim outputFile as StreamWriteroutputFile = File.CreateText("values.txt")For count = 0 To (intValues.Length – 1)
outputFile.WriteLine(intValues(count))Next countoutputFile.Close()------------------------------------------------Dim inputFile as StreamReaderinputFile = File.OpenText("values.txt")For count = 0 To (intValues.Length – 1)
intValues(count) = Val(inputFile.ReadLine)Next countinputFile.Close()
Chapter 9, Slide 26 Starting Out with Visual Basic 3rd Edition
Section 9.2The 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
Chapter 9, Slide 27 Starting Out with Visual Basic 3rd Edition
OpenFileDialog and SaveFileDialog
Windows has a standard method of allowing a user to choose a file to open or save• Provides users the ability to 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
Chapter 9, Slide 28 Starting Out with Visual Basic 3rd Edition
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
Chapter 9, Slide 29 Starting Out with Visual Basic 3rd Edition
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 (*.*)|*.*"
Chapter 9, Slide 30 Starting Out with Visual Basic 3rd Edition
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
Chapter 9, Slide 31 Starting Out with Visual Basic 3rd Edition
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
Chapter 9, Slide 32 Starting Out with Visual Basic 3rd Edition
SaveFileDialog Control SaveFileDialog uses the same methods:
• ShowDialog() The same properties:
• Filter• InitialDirectory• Title• Filename
And the same result constants:• DialogResult.OK• DialogResult.Cancel
Tutorial 9-4 uses these controls in a text editor
Chapter 9, Slide 33 Starting Out with Visual Basic 3rd Edition
ColorDialog Control
Displays a typical Windows color dialog box• Provides users the ability to choose a color
To use the ColorDialog control• Double click the tool in the Toolbox• Appears in component tray• Use cd as standard prefix when naming
The following code sets the text in control lblMessage to the color selected by the usercdColor.ShowDialog()If cdColor.ShowDialog() = DialogResult.OK Then
lblMessage.ForeColor = cdColor.ColorEnd If
Chapter 9, Slide 34 Starting Out with Visual Basic 3rd Edition
FontDialog Control
Displays a Windows font selection dialog box• Allows users to choose font, font size, etc.
To use the FontDialog control• Double click the tool in the Toolbox• Appears in component tray• Use fd as standard prefix when naming
The following code sets the text in control lblMessage to the font selected by the userfdFont.ShowDialog()If fdFont.ShowDialog() = DialogResult.OK Then
lblMessage.Font = fdFont.FontEnd If
Chapter 9, Slide 35 Starting Out with Visual Basic 3rd Edition
Section 9.3The PrintDocument Control
The PrintDocument Control Allows You to Print Data to the Printer
Chapter 9, Slide 36 Starting Out with Visual Basic 3rd Edition
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
Chapter 9, Slide 37 Starting Out with Visual Basic 3rd Edition
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 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 event handler• Basic format of event handler is as follows:
Chapter 9, Slide 38 Starting Out with Visual Basic 3rd Edition
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
DrawString method is formatted as follows:
e.Graphics.DrawString(String, _New Font(FontName, Size, Style), _Brushes.Black, HPos, VPos)
Chapter 9, Slide 39 Starting Out with Visual Basic 3rd Edition
Specifying Fonts, Sizes, Styles Fonts are specified with the string which
names the font to be used• "Times New Roman"
Sizes are specified with a number• 12
Styles are specified with provided constants• FontStyle.Regular• FontStyle.Bold• FontStyle.Underline
Chapter 9, Slide 40 Starting Out with Visual Basic 3rd Edition
Sample PrintPage Event ProcedurePrivate Sub pdPrint_PrintPage(ByVal sender As System.Object, _
ByVal e As System.Drawing.Printing.PrintPageEventArgs) _Handles pdPrint.PrintPage
Dim inputFile As System.IO.StreamReaderDim x As Integer = 10 ‘Horizontal PositionDim y As Integer = 10 ‘Vertical Position
inputFile = System.IO.File.OpenText(filename)Do While inputFile.Peek <> -1
e.Graphics.DrawString(inputFile.ReadLine, _New Font("Courier", 10, FontStyle.Regular), _Brushes.Black, x, y)
y += 12 ‘Increment Vert PosLoopinputFile.Close()End Sub
Tutorial 9-5 adds a print feature to Tutorial 9-4
Chapter 9, Slide 41 Starting Out with Visual Basic 3rd Edition
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
Chapter 9, Slide 42 Starting Out with Visual Basic 3rd Edition
String.Format Example
String.Format("{0, 10}{1, 10}{2, 10}", 50, "Arg 1", 6)
Specifiesthe argument
numberSpecifies field width for arg
negative - left justifiedpositive - right justified
Argument 0Argument 1
Argument 2
Results in the following output:
50 Arg 1 6
10 spaces 10 spaces 10 spaces
Chapter 9, Slide 43 Starting Out with Visual Basic 3rd Edition
Section 9.4Structures
Visual Basic Allows You to Create Your Own Data Types, in Which You May Group Multiple Data Fields
Chapter 9, Slide 44 Starting Out with Visual Basic 3rd Edition
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
Chapter 9, Slide 45 Starting Out with Visual Basic 3rd Edition
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
Chapter 9, Slide 46 Starting Out with Visual Basic 3rd Edition
Structure Declaration Example
Structure EmpPayDataDim empNumber As IntegerDim firstName As StringDim lastName As StringDim hours As SingleDim payRate As DecimalDim grossPay As Decimal
End Structure
Following declares a structure with six fields intended to record employee payroll data
Structure name is EmpPayData
Chapter 9, Slide 47 Starting Out with Visual Basic 3rd Edition
Creating and Initializing a Structure
Dim deptHead As EmpPayData
deptHead.empNumber = 1101deptHead.firstName = "Joanne"deptHead.lastName = "Smith"deptHead.hours = 40deptHead.payRate = 25deptHead.grossPay = deptHead.hours * deptHead.payRate
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
Chapter 9, Slide 48 Starting Out with Visual Basic 3rd Edition
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
Chapter 9, Slide 49 Starting Out with Visual Basic 3rd Edition
Structures Containing Arrays
Structure StudentRecordname As StringtestScores() As Single
End Structure
Dim student As StudentRecordReDim student.TestScores(4)student.name = "Mary McBride"student.testScores(0) = 89student.testScores(1) = 92student.testScores(2) = 84student.testScores(3) = 96student.testScores(4) = 91
Structures can contain arrays Must ReDim after declaring structure variable
Chapter 9, Slide 50 Starting Out with Visual Basic 3rd Edition
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
Tutorial 9-6 examines an application with a structure
Arrays Containing Structures
Dim employees(9) As EmpPayData
' Refer to the empNumber of the first employeeemployees(0).empNumber = 1101
Chapter 9, Slide 51 Starting Out with Visual Basic 3rd Edition
Section 9.5Modifying the Demetris
Leadership Center Application
Modify this application to include the ability to save and retrieve data,
use an array of structure variables instead of parallel arrays,
print the sales report