Chapter 11

41
11-1 lskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjh lskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjh lskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjh lskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjh lskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjh lskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjh lskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjh lskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjh lskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjh lskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjh lskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjh lskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjh lskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjh lskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjh lskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjh lskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjh lskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjh lskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjh lskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjh lskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjh lskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjh lskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjh lskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjh lskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjh

description

 

Transcript of Chapter 11

Page 1: Chapter 11

11-1

aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf

Page 2: Chapter 11

Saving Data and Objects In Files

Chapter1111

McGraw-Hill © 2006 The McGraw-Hill Companies, Inc. All rights reserved.

Page 3: Chapter 11

11-3

Objectives

Declare and instantiate objects in codeStore and retrieve data in files using streamsSave the values from a list box and reload for the next

program runCheck for the end of fileTest whether a file existsDisplay the standard Open File and Save File dialog

box to allow the user to choose or name the file

Page 4: Chapter 11

11-4

Creating Objects

Objects are created by the VB form designerTo create a new object, declare an object of the classThe rules for declaring an object variable are the

same as those for declaring the numeric and string variables

Can use Dim, Public, Private and Friend for accessibility

Location of the declaration determines the scope and lifetime of the object

Page 5: Chapter 11

11-5

Instantiating an Object

Create an instance of the class using New:keyword to actually create a new object

The New Keyword can be used in several different ways:Declare the variable and instantiate in one statement

Used to instantiate an object inside a procedure - localDeclare the variable in one location and instantiate it in

anotherThe object needs to be available in more than once

procedure-module levelInstantiate a new object with a variable name

The object won’t be referred to again in code

Page 6: Chapter 11

11-6

Specifying a Namespace

A qualified name consists of the complete namespace and class name, such as: System.Windows.Forms.Textbox

When a class is referred to in a different namespace there are two choices:Write out the entire namespace and class

Add an Imports statement at the top of the code to specify the namespace and refer only to the class name

Me.messageLablel.Font = New System.Drawing.Font”‘Arial”,12)

Imports System.Drawing

Me.messageLabel.Font – New Font(“Arial”,12)

Page 7: Chapter 11

11-7

Data Files and Project Files74

To save data from one run of the application to the next

Use when there is only a small amount of data that would not warrant the use of a database

Use for Windows applications, the default security policy for the Internet and Intranets does not allow access to disk files

Page 8: Chapter 11

11-8

Data File Terminology

File ==> Entire collection of dataRecords ==> Rows, one per entityFields ==> Columns, data elements

within row

Page 9: Chapter 11

11-9

Sample Data File

Records

Fields

Last Name First Name Phone

Maxwell Harry 909-555-1234

Helm Jennifer 818-555-2222

Colton Craig 909-555-3333

Page 10: Chapter 11

11-10

File Handling Using Streams

Visual Studio handles data files using streamsA stream is designed to transfer a series

of bytes from one location to anotherStreams are objects that have methods and

propertiesFound in the System.IO.namespaceFile handling projects must contain an Imports

statement before the statement declaring the form's class

Page 11: Chapter 11

11-11

File I/O

Reading and writing data in a disk fileWriting = OutputReading = Input

Page 12: Chapter 11

11-12

Writing Data in a File

User inputs data into text boxes—the steps for writing data are:

Declare a new StreamWriter objectAlso declares the name of the data file

Use StreamWriter's WriteLine methodCopies data to a buffer in memory

Call StreamWriter's Close methodTransfers data from buffer to the file and releases

system resources used by the stream

Page 13: Chapter 11

11-13

Instantiating a StreamWriter Object

General FormDefault location for file is where the program executable (.exe) is placed—which is the bin/Debug folder beneath the folder of the current projectCan specify the complete path of the fileCan be specified to append data to an existing file

Specify True to append

Dim ObjectName As New StreamWriter("FileName")

Dim ObjectName As New StreamWriter("FileName", BooleanAppend)

Page 14: Chapter 11

11-14

Declaring a StreamWriter Object - Examples

The StreamWriter object has both a Write and WriteLine method

Dim phoneStreamWriter As New StreamWriter("Phone.txt")

Dim namesStreamWriter As New StreamWriter("C:\MyFiles\Names.txt")

Dim logFileStreamWriter As New StreamWriter("C:\MyFiles\LogFile.txt", True)

Page 15: Chapter 11

11-15

Write and WriteLine Methods

Write MethodPlaces items consecutively in the file with no delimiter

(separator)WriteLine Method

Places an enter (carriage return) between itemsUsed in this chapter

Page 16: Chapter 11

11-16

The WriteLine Method - General Form

DataToWrite argument may be string or numericConverts any numeric data to string and writes

string data in the file

ObjectName.WriteLine(DataToWrite)

Page 17: Chapter 11

11-17

The WriteLine Method - Examples

phoneStreamWriter.WriteLine(nameTextBox.Text)

phoneStreamWriter.WriteLine(phoneTextBox.Text)

namesStreamWriter.WriteLine("Sammy")

bankBalanceStreamWriter.WriteLine(balanceDecimal.ToString( ))

Page 18: Chapter 11

11-18

Button Click Event Procedure

The user enters data into thetext boxes and clicks the Savebutton, which writes the data from the screen to the StreamWrite object and clears the screen

Page 19: Chapter 11

11-19

Closing a File

Use StreamWriter's Close method

Finishes writing all data from the stream's buffer to the disk and releases system resources

Commonly coded in form’s closing event procedure

If the file is not closed it may remain open for an indefinite time and sometimes may become unusable

Page 20: Chapter 11

11-20

Closing a File - Example

Private Sub exitButton_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles exitButton.Click

' Close the file and the form.

phoneStreamWriter.Close( )

Me.Close( )

End Sub

Page 21: Chapter 11

11-21

Viewing the Contents of a File (1 of 2)

Text editor, such as NotepadVisual Studio's IDE

In the Solution Explorer

Select the Project name

Click Show All Files buttonto display the bin folder

Select the file to display in the editor window

Page 22: Chapter 11

11-22

Viewing the Contents of a File (2 of 2)

Page 23: Chapter 11

11-23

Reading Data from a File

The steps for reading the data from a file are:Declare an object of the StreamReader class

Also declares the name of the data fileOpens the file

Use StreamReader's ReadLine methodMay need a loop to retrieve multiple records

Call StreamReader's Close method

Page 24: Chapter 11

11-24

Instantiating a StreamReader Object

The file must exist in the specified location where the application expects it or an exception occurs

Declare the StreamReader object in a procedure and enclose it in a Try/Catch block

Page 25: Chapter 11

11-25

Instantiating a StreamReader Object-Example

General Form

Example

Dim ObjectName As New StreamReader("FileName")

Try

Dim namesStreamReader As New StreamReader("C:\MyFiles\Names.txt")

Catch

MessageBox.Show("File does not exist")

End Try

Page 26: Chapter 11

11-26

Using the ReadLine Method

Use to read previously saved dataEach time it executes, it reads the next line of dataAssign the value from the read to the desired

location, such as a label, text box, or string variable

Example

Me.nameLabel.Text = phoneStreamReader.ReadLine( )

Page 27: Chapter 11

11-27

Checking for the End of the File

Use StreamReader's Peek methodPeek method looks at the next element without

reading itIf you Peek beyond the last element the value

returned is negative 1 (-1)Code an If statement to execute Peek and

compare for <> -1 before readingRead elements in the exact same order as they

were written to obtain valid data

Page 28: Chapter 11

11-28

The File Read Program

Reads the file and displays records on a formEach time the user clicks Next, the program reads and

displays the next record

Page 29: Chapter 11

11-29

Using the File Common Dialog Box

May allow the user to browse and enter the file name at run time

User browses for a folder and filename or enters a new filename

Use the OpenFileDialog common dialog component to display the dialog box

Then use the object's FileName property to open the selected file

Page 30: Chapter 11

11-30

Displaying the Open File Dialog Box

Add OpenFileDialog component to form

At design time set initial properties for Name, CheckFileExists, CheckPathExists, Filter and Title

In code set InitialDirectory property to Application.StartUpPath

Display dialog box using ShowDialog method and retrieve FileName property

Page 31: Chapter 11

11-31

Open File to Read Dialog Box

Files of TypeDetermined by Filter

Property

Page 32: Chapter 11

11-32

Checking for Successful File Open

If the StreamWriter or StreamReader were not instantiated, the file did not open

Use the VB keyword Nothing to check for instantiationAn object that has not been instantiated has a value of

NothingSyntax important0use the keyword IsNot rather than

the not equal operator (<>)

Page 33: Chapter 11

11-33

' Is the file already open?

If Not phoneStreamWriter IsNot Nothing Then

phoneStreamWriter.Close( )

End If

Using Nothing Keyword

Must use Keyword Is rather than equal sign

Page 34: Chapter 11

11-34

Checking for Already Open File

It’s possible that a user may select the File/Open menu item twice—this causes a problem

A second open file instantiates another file stream-the Close method never executes for the first file

Always check for an active instance of the file stream

Page 35: Chapter 11

11-35

Using the Save File Dialog Component

In addition to the OpenFile Dialog a SaveFileDialog component can be displayed—displays the standard system Save As dialog box

The Save FileDialog allows the user to brose and enter a filename to saveHas most of the same properties as the OpenFileDialog

componentBy default, the SaveFileDialog component checks for

an already existing file and displays a dialog box asking the user whether to replace the existing file

Page 36: Chapter 11

11-36

Saving the Contents of a List Box

Do not assign values at design time, when program begins, open data file and read items into Items collection of List Box

If user makes changes to list, ask whether to save list when program ends

Include a menu option to save listIf file of list elements does not exist when program

begins, allow user to create new list by adding items

Page 37: Chapter 11

11-37

Loading the List Box

Read the file into the list in Form_LoadLoop through the file until all elements are readUse the Items.Add method to add the data

elements to the list

Dim coffeeFlavor As String' Read all elements into the list.Do Until flavorsStreamReader.Peek = -1 coffeeFlavorString = flavorStreamReader.ReadLine( ) Me.coffeeComboBox.Items.Add(coffeeFlavorString)Loop

Page 38: Chapter 11

11-38

Checking for Existence of the File

When the StreamReader object is created, the constructor makes sure the file exists

If it does not exist, give the user optionsTry to locate the data file againExit the programBegin with an empty list, add items, and create a new

file

Page 39: Chapter 11

11-39

Saving the File

Provide a menu option for the user to save the fileOpen a StreamWriter object Loop through the Items collection of the list box,

saving each element with a WriteLine method

Page 40: Chapter 11

11-40

Querying the User to Save

Good idea to ask users if they want to save any changes made before program ends

Use a module-level Boolean variable, isDirtyBoolean, to keep track of changesIn procedures that allow changes, set variable to

TrueAfter saving file set variable to False

Page 41: Chapter 11

11-41

The FormClosing Event Procedure

FormClosing event procedure is in the best location to ask user to save the file

Closing event executes before the form closes no matter how user exits program or even Windows