Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Chapter 11

997 views

Published on

Published in: Education, Sports, Technology
  • Be the first to comment

  • Be the first to like this

Chapter 11

  1. 1. aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf
  2. 2. Saving Data and Objects In Files Chapter 11 McGraw-Hill © 2006 The McGraw-Hill Companies, Inc. All rights reserved.
  3. 3. Objectives <ul><li>Declare and instantiate objects in code </li></ul><ul><li>Store and retrieve data in files using streams </li></ul><ul><li>Save the values from a list box and reload for the next program run </li></ul><ul><li>Check for the end of file </li></ul><ul><li>Test whether a file exists </li></ul><ul><li>Display the standard Open File and Save File dialog box to allow the user to choose or name the file </li></ul>
  4. 4. Creating Objects <ul><li>Objects are created by the VB form designer </li></ul><ul><li>To create a new object, declare an object of the class </li></ul><ul><li>The rules for declaring an object variable are the same as those for declaring the numeric and string variables </li></ul><ul><li>Can use Dim, Public, Private and Friend for accessibility </li></ul><ul><li>Location of the declaration determines the scope and lifetime of the object </li></ul>
  5. 5. Instantiating an Object <ul><li>Create an instance of the class using New:keyword to actually create a new object </li></ul><ul><li>The New Keyword can be used in several different ways: </li></ul><ul><ul><li>Declare the variable and instantiate in one statement </li></ul></ul><ul><ul><ul><li>Used to instantiate an object inside a procedure - local </li></ul></ul></ul><ul><ul><li>Declare the variable in one location and instantiate it in another </li></ul></ul><ul><ul><ul><li>The object needs to be available in more than once procedure-module level </li></ul></ul></ul><ul><ul><li>Instantiate a new object with a variable name </li></ul></ul><ul><ul><ul><li>The object won’t be referred to again in code </li></ul></ul></ul>
  6. 6. Specifying a Namespace <ul><li>A qualified name consists of the complete namespace and class name, such as: System.Windows.Forms.Textbox </li></ul><ul><li>When a class is referred to in a different namespace there are two choices: </li></ul><ul><ul><li>Write out the entire namespace and class </li></ul></ul><ul><ul><li>Add an Imports statement at the top of the code to specify the namespace and refer only to the class name </li></ul></ul>Me.messageLablel.Font = New System.Drawing.Font”‘Arial”,12) Imports System.Drawing Me.messageLabel.Font – New Font(“Arial”,12)
  7. 7. Data Files and Project Files74 <ul><li>To save data from one run of the application to the next </li></ul><ul><li>Use when there is only a small amount of data that would not warrant the use of a database </li></ul><ul><li>Use for Windows applications, the default security policy for the Internet and Intranets does not allow access to disk files </li></ul>
  8. 8. Data File Terminology <ul><li>File ==> Entire collection of data </li></ul><ul><li>Records ==> Rows, one per entity </li></ul><ul><li>Fields ==> Columns, data elements within row </li></ul>
  9. 9. 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
  10. 10. File Handling Using Streams <ul><li>Visual Studio handles data files using streams </li></ul><ul><li>A s tream is designed to transfer a series of bytes from one location to another </li></ul><ul><li>Streams are objects that have methods and properties </li></ul><ul><li>Found in the System.IO.namespace </li></ul><ul><li>File handling projects must contain an Imports statement before the statement declaring the form's class </li></ul>
  11. 11. File I/O <ul><li>Reading and writing data in a disk file </li></ul><ul><ul><li>Writing = Output </li></ul></ul><ul><ul><li>Reading = Input </li></ul></ul>
  12. 12. Writing Data in a File <ul><li>User inputs data into text boxes—the steps for writing data are: </li></ul><ul><li>Declare a new StreamWriter object </li></ul><ul><ul><li>Also declares the name of the data file </li></ul></ul><ul><li>Use StreamWriter's WriteLine method </li></ul><ul><ul><li>Copies data to a buffer in memory </li></ul></ul><ul><li>Call StreamWriter's Close method </li></ul><ul><ul><li>Transfers data from buffer to the file and releases system resources used by the stream </li></ul></ul>
  13. 13. Instantiating a StreamWriter Object <ul><li>General Form </li></ul><ul><ul><li>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 </li></ul></ul><ul><ul><li>Can specify the complete path of the file </li></ul></ul><ul><ul><li>Can be specified to append data to an existing file </li></ul></ul><ul><ul><ul><li>Specify True to append </li></ul></ul></ul>Dim ObjectName As New StreamWriter ( &quot;FileName&quot; ) Dim ObjectName As New StreamWriter ( &quot;FileName&quot;, BooleanAppend )
  14. 14. Declaring a StreamWriter Object - Examples <ul><li>The StreamWriter object has both a Write and WriteLine method </li></ul>Dim phoneStreamWriter As New StreamWriter (&quot;Phone.txt&quot;) Dim namesStreamWriter As New StreamWriter (&quot;C:MyFilesNames.txt&quot;) Dim logFileStreamWriter As New StreamWriter (&quot;C:MyFilesLogFile.txt&quot;, True)
  15. 15. Write and WriteLine Methods <ul><li>Write Method </li></ul><ul><ul><li>Places items consecutively in the file with no delimiter (separator) </li></ul></ul><ul><li>WriteLine Method </li></ul><ul><ul><li>Places an enter (carriage return) between items </li></ul></ul><ul><ul><li>Used in this chapter </li></ul></ul>
  16. 16. The WriteLine Method - General Form <ul><li>DataToWrite argument may be string or numeric </li></ul><ul><li>Converts any numeric data to string and writes string data in the file </li></ul>ObjectName . WriteLine ( DataToWrite )
  17. 17. The WriteLine Method - Examples phoneStreamWriter . WriteLine (nameTextBox.Text) phoneStreamWriter . WriteLine (phoneTextBox.Text) namesStreamWriter . WriteLine (&quot;Sammy&quot;) bankBalanceStreamWriter . WriteLine (balanceDecimal.ToString( ))
  18. 18. 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
  19. 19. Closing a File <ul><li>Use StreamWriter's Close method </li></ul><ul><li>Finishes writing all data from the stream's buffer to the disk and releases system resources </li></ul><ul><li>Commonly coded in form’s closing event procedure </li></ul><ul><li>If the file is not closed it may remain open for an indefinite time and sometimes may become unusable </li></ul>
  20. 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
  21. 21. Viewing the Contents of a File (1 of 2) <ul><li>Text editor, such as Notepad </li></ul><ul><li>Visual Studio's IDE </li></ul><ul><ul><li>In the Solution Explorer </li></ul></ul><ul><ul><ul><li>Select the Project name </li></ul></ul></ul><ul><ul><ul><li>Click Show All Files button to display the bin folder </li></ul></ul></ul><ul><ul><ul><li>Select the file to display in the editor window </li></ul></ul></ul>
  22. 22. Viewing the Contents of a File (2 of 2)
  23. 23. Reading Data from a File <ul><li>The steps for reading the data from a file are: </li></ul><ul><ul><li>Declare an object of the StreamReader class </li></ul></ul><ul><ul><ul><li>Also declares the name of the data file </li></ul></ul></ul><ul><ul><ul><li>Opens the file </li></ul></ul></ul><ul><ul><li>Use StreamReader's ReadLine method </li></ul></ul><ul><ul><ul><li>May need a loop to retrieve multiple records </li></ul></ul></ul><ul><ul><li>Call StreamReader's Close method </li></ul></ul>
  24. 24. Instantiating a StreamReader Object <ul><li>The file must exist in the specified location where the application expects it or an exception occurs </li></ul><ul><li>Declare the StreamReader object in a procedure and enclose it in a Try/Catch block </li></ul>
  25. 25. Instantiating a StreamReader Object-Example <ul><li>General Form </li></ul><ul><li>Example </li></ul>Dim ObjectName As New StreamReader ( &quot;FileName&quot; ) Try Dim namesStreamReader As New S treamReader (&quot;C:MyFilesNames.txt&quot;) Catch MessageBox.Show(&quot;File does not exist&quot;) End Try
  26. 26. Using the ReadLine Method <ul><li>Use to read previously saved data </li></ul><ul><li>Each time it executes, it reads the next line of data </li></ul><ul><li>Assign the value from the read to the desired location, such as a label, text box, or string variable </li></ul><ul><li>Example </li></ul>Me.nameLabel.Text = phoneStreamReader . ReadLine ( )
  27. 27. Checking for the End of the File <ul><li>Use StreamReader's Peek method </li></ul><ul><li>Peek method looks at the next element without reading it </li></ul><ul><li>If you Peek beyond the last element the value returned is negative 1 (-1) </li></ul><ul><li>Code an If statement to execute Peek and compare for <> -1 before reading </li></ul><ul><li>Read elements in the exact same order as they were written to obtain valid data </li></ul>
  28. 28. The File Read Program <ul><li>Reads the file and displays records on a form </li></ul><ul><li>Each time the user clicks Next, the program reads and displays the next record </li></ul>
  29. 29. Using the File Common Dialog Box <ul><li>May allow the user to browse and enter the file name at run time </li></ul><ul><li>User browses for a folder and filename or enters a new filename </li></ul><ul><li>Use the OpenFileDialog common dialog component to display the dialog box </li></ul><ul><li>Then use the object's FileName property to open the selected file </li></ul>
  30. 30. Displaying the Open File Dialog Box <ul><li>Add OpenFileDialog component to form </li></ul><ul><li>At design time set initial properties for Name, CheckFileExists, CheckPathExists, Filter and Title </li></ul><ul><li>In code set InitialDirectory property to Application.StartUpPath </li></ul><ul><li>Display dialog box using ShowDialog method and retrieve FileName property </li></ul>
  31. 31. Open File to Read Dialog Box Files of Type Determined by Filter Property
  32. 32. Checking for Successful File Open <ul><li>If the StreamWriter or StreamReader were not instantiated, the file did not open </li></ul><ul><li>Use the VB keyword Nothing to check for instantiation </li></ul><ul><li>An object that has not been instantiated has a value of Nothing </li></ul><ul><li>Syntax important0use the keyword IsNot rather than the not equal operator (<>) </li></ul>
  33. 33. 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
  34. 34. Checking for Already Open File <ul><li>It’s possible that a user may select the File/Open menu item twice—this causes a problem </li></ul><ul><li>A second open file instantiates another file stream-the Close method never executes for the first file </li></ul><ul><li>Always check for an active instance of the file stream </li></ul>
  35. 35. Using the Save File Dialog Component <ul><li>In addition to the OpenFile Dialog a SaveFileDialog component can be displayed—displays the standard system Save As dialog box </li></ul><ul><li>The Save FileDialog allows the user to brose and enter a filename to save </li></ul><ul><ul><li>Has most of the same properties as the OpenFileDialog component </li></ul></ul><ul><li>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 </li></ul>
  36. 36. Saving the Contents of a List Box <ul><li>Do not assign values at design time, when program begins, open data file and read items into Items collection of List Box </li></ul><ul><li>If user makes changes to list, ask whether to save list when program ends </li></ul><ul><li>Include a menu option to save list </li></ul><ul><li>If file of list elements does not exist when program begins, allow user to create new list by adding items </li></ul>
  37. 37. Loading the List Box <ul><li>Read the file into the list in Form_Load </li></ul><ul><li>Loop through the file until all elements are read </li></ul><ul><li>Use the Items.Add method to add the data elements to the list </li></ul>Dim coffeeFlavor As String ' Read all elements into the list. Do Until flavorsStreamReader.Peek = -1 coffeeFlavorString = flavorStreamReader.ReadLine( ) Me.coffeeComboBox.Items.Add(coffeeFlavorString) Loop
  38. 38. Checking for Existence of the File <ul><li>When the StreamReader object is created, the constructor makes sure the file exists </li></ul><ul><li>If it does not exist, give the user options </li></ul><ul><ul><li>Try to locate the data file again </li></ul></ul><ul><ul><li>Exit the program </li></ul></ul><ul><ul><li>Begin with an empty list, add items, and create a new file </li></ul></ul>
  39. 39. Saving the File <ul><li>Provide a menu option for the user to save the file </li></ul><ul><li>Open a StreamWriter object </li></ul><ul><li>Loop through the Items collection of the list box, saving each element with a WriteLine method </li></ul>
  40. 40. Querying the User to Save <ul><li>Good idea to ask users if they want to save any changes made before program ends </li></ul><ul><li>Use a module-level Boolean variable, isDirtyBoolean , to keep track of changes </li></ul><ul><ul><li>In procedures that allow changes, set variable to True </li></ul></ul><ul><ul><li>After saving file set variable to False </li></ul></ul>
  41. 41. The FormClosing Event Procedure <ul><li>FormClosing event procedure is in the best location to ask user to save the file </li></ul><ul><li>Closing event executes before the form closes no matter how user exits program or even Windows </li></ul>

×