Chapter 9 Files, Printing, and Structure Topics Using Files The OpenFileDialog, SaveFileDialog, FontDialog, and ColorDialog Controls The PrintDocument.

Slides:



Advertisements
Similar presentations
Files, Printing, and Structures
Advertisements

Lists, Loops, Validation, and More
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 9- 1 STARTING OUT WITH Visual Basic 2008 FOURTH EDITION Tony Gaddis.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 24.1 Test-Driving the Ticket Information Application.
Working with Intrinsic Controls and ActiveX Controls
Copyright © 2012 Pearson Education, Inc. Chapter 11 MORE WINDOWS CONTROLS & STANDARD DIALOG BOXES.
Addison Wesley is an imprint of © 2011 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Chapter 9 Files, Printing, and Structures.
Copyright © 2014 Pearson Education, Inc. Chapter 9 Files, Printing, and Structures.
Chapter 11 Data Files Copyright © 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved. McGraw-Hill.
Chapter 5 Menus, Common Dialog Boxes, Sub Procedures, and Function Procedures Copyright © 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved.
IS 1181 IS 118 Introduction to Development Tools VB Chapter 06.
VBA Modules, Functions, Variables, and Constants
Chapter 9: Sequential Access Files and Printing
Microsoft Visual Basic 2005: Reloaded Second Edition Chapter 9 Structures and Sequential Access Files.
Chapter 9 Files I/O: Files, Records and Fields. Basics of File Input and Output Have created both input and outputs from programs. Persistent data: What.
File Handling. Data Files Programs that can only get data from the user interface are limited. –data must be entered each time. –only small amounts of.
Microsoft Visual Basic 2008 CHAPTER NINE Using Arrays and File Handling.
Microsoft Visual Basic 2005 CHAPTER 9 Using Arrays and File Handling.
Using Arrays and File Handling
5-1 aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf.
McGraw-Hill © 2009 The McGraw-Hill Companies, Inc. All rights reserved. Chapter 5 Menus, Common Dialog Boxes, Sub Procedures, and Function Procedures.
Chapter 5 Menus, Common Dialog Boxes, and Methods Programming in C#.NET © 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
XP New Perspectives on Microsoft Word 2002 Tutorial 31 Microsoft Word 2002 Tutorial 3 – Creating a Multiple-Page Report.
Visual Basic.NET Comprehensive Concepts and Techniques Chapter 7 Using Menus, Common Dialogs, Procedures, Functions, and Arrays.
Chapter 5 Menus, Common Dialog Boxes, Sub Procedures, and Function Procedures Copyright © 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved.
Chapter 10: Structures and Sequential Access Files
Chapter Ten Structures and Sequential Access Files Programming with Microsoft Visual Basic th Edition.
1 Κατανεμημένες Διαδικτυακές Εφαρμογές Πολυμέσων Γιάννης Πετράκης.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Ticket Information Application Introducing Sequential-Access Files.
11-1 aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf.
Chapter Ten Structures and Sequential Access Files Programming with Microsoft Visual Basic th Edition.
Lecture Set 12 Sequential Files and Structures Part A – Dialog Boxes, Filters, Directories.
Working with the VB IDE. Running a Program u Clicking the”start” tool begins the program u The “break” tool pauses a program in mid-execution u The “end”
Chapter 10 Sequential Files and Structures. Class 10: Sequential Files Work with different types of sequential files Read sequential files based on the.
Reference: Lecturer Lecturer Reham O. Al-Abdul Jabba lectures for cap211 Files and Streams- I.
File I/O What We’ll Cover –Visual Basic Techniques for Text Files –.NET Techniques for Text Files What We’ll Not Cover –Binary File I/O –XML File I/O.
Tutorial 9: Sequential Access Files and Printing1 Tutorial 9 Sequential Access Files and Printing.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 9- 1.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.
Copyright © 2012 Pearson Education, Inc. Chapter 5 Loops, File, and Random Numbers.
Week Files, Printing, and Structures Introduction Saving data to sequential text files Reading the data back into an application Using the OpenFileDialog,
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
Programming with Microsoft Visual Basic 2008 Fourth Edition Chapter Ten Structures and Sequential Access Files.
Introduction to Files in VB Chapter 9.1, 9.3. Overview u Data Files  random access  sequential u Working with sequential files  open, read, write,
Creating Menus Menu Bar – behaves like standard Windows menus Can be used in place of or in addition to buttons to execute a procedure Menu items are controls.
Chapter 5 Menus, Sub Procedures and Sub Functions Programming In Visual Basic.NET.
List Boxes and Combo Boxes Provides a list of items to select from Various styles — choose based on Space available Need to select from an existing list.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Student Grades Application Introducing Two-Dimensional Arrays and RadioButton.
Tutorial 81 Field, Record, Data File Field - a single item of information about a person, place, or thing Record - a group of related fields that contain.
Microsoft Visual Basic 2005: Reloaded Second Edition Chapter 9 Structures and Sequential Access Files.
Visual Basic.NET Programming for the Rest of Us Keith Mulbery Utah Valley State College.
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. Chapter 11 Data Files.
Files and Streams. What is a file? Up until now, any stored data within a program is lost when the program closes. A file is a permanent way to store.
Files and Streams. Objectives Learn about the classes that support file input/output Understand the concept of abstraction and how it related to the file.
Making Interactive Programs with Visual Basic .NET
Chapter 4.  Variables – named memory location that stores a value.  Variables allows the use of meaningful names which makes the code easier to read.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
1 Displaying Dialog Boxes Kashef Mughal. 2 Midterm Stats Here we go  Average was  Low was 116  High was 184  Mid Quarter Grade - check any.
Files.
Files and Streams.
Topics Introduction to File Input and Output
Chapter 3.5 Input and Output
Files, Printing, and Structures
Tutorial 9 Sequential Access Files and Printing
CIS16 Application Development and Programming using Visual Basic.net
Tony Gaddis Kip Irvine STARTING OUT WITH Visual Basic 2008
Topics Introduction to File Input and Output
Files and Streams.
Topics Introduction to File Input and Output
Chapter 11 Saving Data and Objects In Files
Presentation transcript:

Chapter 9 Files, Printing, and Structure Topics Using Files The OpenFileDialog, SaveFileDialog, FontDialog, and ColorDialog Controls The PrintDocument Control Structures

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

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

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

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 cassette tape and a CD

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 Dim phoneFile As StreamWriter –Call CreateText method passing the filename phoneFile = File.CreateText("phonelist.txt") –This 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

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 Dim phoneFile As StreamWriter –Call AppendText method passing the filename phoneFile = File.AppendText("phonelist.txt") –This Method AppendText 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

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

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

Writing Data to a File Example Dim studentFile As StreamWriter studentFile = File.CreateText("StudentData.txt") studentFile.WriteLine("Jim") studentFile.WriteLine(95) studentFile.WriteLine("Karen") studentFile.WriteLine(98) studentFile.WriteLine("Bob") studentFile.WriteLine(82) studentFile.Close() Jim 95 Karen 98 Bob 82 The Resulting File, StudentData.txt

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)

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 Tutorial 9-1 provides an example of an application that writes data to a file

Appending to a File If opening an existing file with CreateText –Existing contents are deleted –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")

Appending a File Example 'Declare an object variable Dim friendFile as StreamWriter 'Open the file friendFile = File.AppendText("MyFriends.txt") 'Write the data friendFile.WriteLine("Bill Johnson") friendFile.WriteLine(30) friendFile.WriteLine("36 Oak Street") 'Close the file friendFile.Close() friendFile “After” Jim Weaver 30 P.O. Box 124 Mary Duncan Elm Street Karen Warren Love Lane friendFile “Before” Jim Weaver 30 P.O. Box 124 Mary Duncan Elm Street Karen Warren Love Lane Bill Johnson Oak Street

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 StreamReader ObjectVar = File.OpenText(Filename) Dim phoneFile As StreamReader phoneFile = File.OpenText("phonelist.txt")

Reading Data from a File The ReadLine method of a StreamReader object actually reads data from the file dataVar = 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 StreamReader custFile = File.OpenText("customer.txt") custName = custFile.ReadLine() custName holds the data read from the file StreamReader also has a Close method

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) Else MessageBox.Show(filename & " does not exist.") End If

Detecting End of 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 Dim scoresFile As StreamReader Dim strInput As String scoresFile = File.OpenText("Scores.txt") Do Until scoresFile.Peek() = -1 strInput = scoresFile.ReadLine() lstResults.Items.Add(input) Loop scoresFile.Close()

Detecting End of File (Cont’d) The EndofStream method also tests if you’ve reached end of file (no more characters to read) –Format is objectvar.EndOfStream –If no more characters, the value True is returned Dim scoresFile As StreamReader Dim strInput As String scoresFile = File.OpenText("Scores.txt") Do Until scoresFile.EndOfStream() strInput = scoresFile.ReadLine() lstResults.Items.Add(input) Loop scoresFile.Close()

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 StreamReader Dim strInput As String textFile = File.OpenText("names.txt") strInput = textFile.ReadToEnd textFile.Close()

Write Then Read Entire Array Dim intValues(9) As Integer Dim outputFile as StreamWriter outputFile = File.CreateText("values.txt") For intCount = 0 To intValues.Length – 1 outputFile.WriteLine(intValues(intCount)) Next outputFile.Close() Dim inputFile as StreamReader inputFile = File.OpenText("values.txt") For intCount = 0 To intValues.Length – 1 intValues(intCount) = CInt(inputFile.ReadLine) Next inputFile.Close()

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

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

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 (*.*)|*.*"

Open Dialog Box Example InitialDirectory property Title property Filter property

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

ColorDialog Control Displays a typical Windows color dialog box –Provides users the ability to choose a color

ColorDialog Control 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 user cdColor.ShowDialog() If cdColor.ShowDialog() = DialogResult.OK Then lblMessage.ForeColor = cdColor.Color End If

FontDialog Control Displays a Windows font selection dialog box –Allows users to choose font, font size, etc.

FontDialog Control 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 user fdFont.ShowDialog() If fdFont.ShowDialog() = DialogResult.OK Then lblMessage.Font = fdFont.Font End If

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

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:

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)

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

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 StreamReader Dim intX As Integer = 10'Horizontal Position Dim 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 Pos Loop inputFile.Close() End Sub Tutorial 9-5 adds a print feature to Tutorial 9-4

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

String.Format Example String.Format("{0, 7}{1, -10}{2, 7}", 50, "Arg1", 6) Specifies the argument number Specifies field width for arg negative - left justified positive - right justified Argument 0 Argument 1 Argument 2 Results in the following output: 50Arg spaces10 spaces Left Justified 7 spaces

Other OpenFileDialog Properties InitialDirectory property specifies folder to use –Default if not specified is the 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

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

Structures A Visual Basic programmer may also create new data types, called user-defined data types (UDT). Two kinds of UDTs: structure and class. This chapter discusses the use of structure and Chapter 12 the use of class.

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

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 StructureName FieldDeclarations End Structure

Structure Declaration Example Structure EmpPayData Dim intEmpNumber As Integer Dim strFirstName As String Dim strLastName As String Dim sngHours As Single Dim decPayRate As Decimal Dim decGrossPay As Decimal End Structure Following declares a structure with six fields intended to record employee payroll data Structure name is EmpPayData

Creating and Initializing a Structure Dim deptHead As EmpPayData deptHead.intEmpNumber = 1101 deptHead.strFirstName = "Joanne" deptHead.strLastName = "Smith" deptHead.sngHours = 40 deptHead.decPayRate = 25 deptHead.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

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 *.decPayRate End With End Sub

Structures Containing Arrays Structure StudentRecord Dim strName As String Dim sngTestScores() As Single End Structure Dim student As StudentRecord ReDim student.sngTestScores(4) student.strName = "Mary McBride" student.sngTestScores(0) = 89 Student.sngTestScores(1) = 92 Student.sngTestScores(2) = 84 Student.sngTestScores(3) = 96 Student.sngTestScores(4) = 91 Structures can contain dynamic arrays Must ReDim after declaring structure variable

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 employee employees(0).empNumber = 1101