• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Chapter 11
 

Chapter 11

on

  • 1,160 views

 

Statistics

Views

Total Views
1,160
Views on SlideShare
1,160
Embed Views
0

Actions

Likes
0
Downloads
10
Comments
0

0 Embeds 0

No embeds

Accessibility

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • Brief description on how to navigate within this presentation (ppt) The first time a Key Term from the chapter is used in the ppt it will display in blue Gold colored text boxes display coding examples Slides will be numbered (# of #) when multiple slides on same topic (Slide title) Speaker notes are included where appropriate for slides (*)Denotes either a comment for page reference to textbook or slide reference in ppt
  • Projects contain many objects such as forms and controls
  • Declaring an object variable does not create the object-it only creates the identifier (name) and object type
  • Data can be read and written to a disk—user entering data into text boxes that will be stored in a file is called writing or output; retrieving data from the file is reading or input In VB, the simplest way to read and write small amounts of data is to the StreamReader and StreamWriter objects Usually the StreamWriter code is written first to create the data file and then the StreamReader code to read the file that has been created
  • Declaring a new StreamWriter object opens the file—the file must be open before it can written to—if a file does not exist a new one is created If a full path is not used in the filename, then instantiate the StreamWriter object in a Try/Catch block in case the path does not exist
  • *The differences between Write and WriteLine methods are discussed in the next slide
  • If inputting data from the user and writing in a file, generally the WriteLine is placed in a button click event procedure so that one record at a time can be written
  • When finished writing data in a file the file must be closed
  • After running a project it can be viewed--
  • StreamReader Class is used to read the data from a file that is created with a StreamWriter
  • Use the StreamReader’s Peek method to tell when there is no more data in a file The ReadLine method does not throw an exception when you attempt to read past the end of a file
  • *The previous data file examples included hard-coded file names (and paths) *Refer to the table on p. 432 for the OpenFileDialog Component Properties
  • The user may click on the Cancel button of the Open File dialog box—check the DialogResult for Cancel If the user does click Cancel, that presents one more tasks for the program: A StreamWriter object that isn’t open cannot be closed
  • *The next slide provides an example of using the correct syntax
  • Beginning with an empty list is a good way to crate the file in the first place
  • Standard practice in programming is to refer to the data as “dirty” if changes have been made—thus the name for the variable is DirtyBoolean Just before the project ends, check the value of isDirtyBoolean; if True, ask the user if he or she wants to save; if False, just exit without a message

Chapter 11 Chapter 11 Presentation Transcript

  • aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf
  • Saving Data and Objects In Files Chapter 11 McGraw-Hill © 2006 The McGraw-Hill Companies, Inc. All rights reserved.
  • Objectives
    • Declare and instantiate objects in code
    • Store and retrieve data in files using streams
    • Save the values from a list box and reload for the next program run
    • Check for the end of file
    • Test whether a file exists
    • Display the standard Open File and Save File dialog box to allow the user to choose or name the file
  • Creating Objects
    • Objects are created by the VB form designer
    • To create a new object, declare an object of the class
    • The 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
  • 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 - local
      • Declare the variable in one location and instantiate it in another
        • The object needs to be available in more than once procedure-module level
      • Instantiate a new object with a variable name
        • The object won’t be referred to again in code
  • 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)
  • 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
  • Data File Terminology
    • File ==> Entire collection of data
    • Records ==> Rows, one per entity
    • Fields ==> Columns, data elements within row
  • Sample Data File Records Fields 909-555-3333 Craig Colton 818-555-2222 Jennifer Helm 909-555-1234 Harry Maxwell Phone First Name Last Name
  • File Handling Using Streams
    • Visual Studio handles data files using streams
    • A s tream is designed to transfer a series of bytes from one location to another
    • Streams are objects that have methods and properties
    • Found in the System.IO.namespace
    • File handling projects must contain an Imports statement before the statement declaring the form's class
  • File I/O
    • Reading and writing data in a disk file
      • Writing = Output
      • Reading = Input
  • Writing Data in a File
    • User inputs data into text boxes—the steps for writing data are:
    • Declare a new StreamWriter object
      • Also declares the name of the data file
    • Use StreamWriter's WriteLine method
      • Copies data to a buffer in memory
    • Call StreamWriter's Close method
      • Transfers data from buffer to the file and releases system resources used by the stream
  • Instantiating a StreamWriter Object
    • General Form
      • Default location for file is where the program executable (.exe) is placed—which is the bin/Debug folder beneath the folder of the current project
      • Can specify the complete path of the file
      • Can 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 )
  • 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:MyFilesNames.txt") Dim logFileStreamWriter As New StreamWriter ("C:MyFilesLogFile.txt", True)
  • Write and WriteLine Methods
    • Write Method
      • Places items consecutively in the file with no delimiter (separator)
    • WriteLine Method
      • Places an enter (carriage return) between items
      • Used in this chapter
  • The WriteLine Method - General Form
    • DataToWrite argument may be string or numeric
    • Converts any numeric data to string and writes string data in the file
    ObjectName . WriteLine ( DataToWrite )
  • The WriteLine Method - Examples phoneStreamWriter . WriteLine (nameTextBox.Text) phoneStreamWriter . WriteLine (phoneTextBox.Text) namesStreamWriter . WriteLine ("Sammy") bankBalanceStreamWriter . WriteLine (balanceDecimal.ToString( ))
  • Button Click Event Procedure The user enters data into the text boxes and clicks the Save button, which writes the data from the screen to the StreamWrite object and clears the screen
  • 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
  • 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
  • Viewing the Contents of a File (1 of 2)
    • Text editor, such as Notepad
    • Visual Studio's IDE
      • In the Solution Explorer
        • Select the Project name
        • Click Show All Files button to display the bin folder
        • Select the file to display in the editor window
  • Viewing the Contents of a File (2 of 2)
  • 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 file
        • Opens the file
      • Use StreamReader's ReadLine method
        • May need a loop to retrieve multiple records
      • Call StreamReader's Close method
  • 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
  • Instantiating a StreamReader Object-Example
    • General Form
    • Example
    Dim ObjectName As New StreamReader ( "FileName" ) Try Dim namesStreamReader As New S treamReader ("C:MyFilesNames.txt") Catch MessageBox.Show("File does not exist") End Try
  • Using the ReadLine Method
    • Use to read previously saved data
    • Each time it executes, it reads the next line of data
    • Assign the value from the read to the desired location, such as a label, text box, or string variable
    • Example
    Me.nameLabel.Text = phoneStreamReader . ReadLine ( )
  • Checking for the End of the File
    • Use StreamReader's Peek method
    • Peek method looks at the next element without reading it
    • If 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 reading
    • Read elements in the exact same order as they were written to obtain valid data
  • The File Read Program
    • Reads the file and displays records on a form
    • Each time the user clicks Next, the program reads and displays the next record
  • 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
  • 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
  • Open File to Read Dialog Box Files of Type Determined by Filter Property
  • 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 instantiation
    • An object that has not been instantiated has a value of Nothing
    • Syntax important0use the keyword IsNot rather than the not equal operator (<>)
  • Using Nothing Keyword ' Is the file already open? If Not phoneStreamWriter IsNot Nothing Then phoneStreamWriter . Close( ) End If Must use Keyword Is rather than equal sign
  • 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
  • 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 save
      • Has most of the same properties as the OpenFileDialog component
    • By default, the SaveFileDialog component checks for an already existing file and displays a dialog box asking the user whether to replace the existing file
  • 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 list
    • If file of list elements does not exist when program begins, allow user to create new list by adding items
  • Loading the List Box
    • Read the file into the list in Form_Load
    • Loop through the file until all elements are read
    • Use 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
  • 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 options
      • Try to locate the data file again
      • Exit the program
      • Begin with an empty list, add items, and create a new file
  • Saving the File
    • Provide a menu option for the user to save the file
    • Open a StreamWriter object
    • Loop through the Items collection of the list box, saving each element with a WriteLine method
  • 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 changes
      • In procedures that allow changes, set variable to True
      • After saving file set variable to False
  • 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