Presentation is loading. Please wait.

Presentation is loading. Please wait.

11-1 aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf.

Similar presentations


Presentation on theme: "11-1 aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf."— Presentation transcript:

1 11-1 aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf

2 Saving Data and Objects In Files Chapter 11 McGraw-Hill© 2006 The McGraw-Hill Companies, Inc. All rights reserved.

3 11-3 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

4 11-4 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

5 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 - 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

6 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.messageLabel.Font = New System.Drawing.Font(“Arial”,12) Imports System.Drawing Me.messageLabel.Font – New Font(“Arial”,12)

7 11-7 Data Files 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

8 11-8 Data File Terminology File ==>Entire collection of data Records==>Rows, one per entity Fields==>Columns, data elements within row

9 11-9 Sample Data File Records Fields Last NameFirst NamePhone MaxwellHarry909-555-1234 HelmJennifer818-555-2222 ColtonCraig909-555-3333

10 11-10 File Handling Using Streams Visual Studio handles data files using streams A stream 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

11 11-11 File I/O Reading and writing data in a disk file Writing = Output Reading = Input

12 11-12 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

13 11-13 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)

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

15 11-15 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

16 11-16 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)

17 11-17 The WriteLine Method - Examples phoneStreamWriter.WriteLine(nameTextBox.Text) phoneStreamWriter.WriteLine(phoneTextBox.Text) namesStreamWriter.WriteLine("Sammy") bankBalanceStreamWriter.WriteLine(balanceDecimal.ToString( ))

18 11-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 StreamWriter object and clears the screen

19 11-19 Saving a Record in a File - Example Private Sub saveButton_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles saveButton.Click ' Save the record to the file. ' Write to already-open stream. With Me phoneStreamWriter.WriteLine(.nameTextBox.Text) phoneStreamWriter.WriteLine(.phoneTextBox.Text) With.nameTextBox.Clear().Focus() End With.phoneTextBox.Clear() End With End Sub

20 11-20 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 a program’s Exit command or the form’s FormClosing event procedure If the file is not closed it may remain open for an indefinite time and sometimes may become unusable

21 11-21 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

22 11-22 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

23 11-23 Viewing the Contents of a File (2 of 2)

24 11-24 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

25 11-25 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

26 11-26 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

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

28 11-28 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) Read elements in the exact same order as they were written to obtain valid data If phoneStreamReader.Peek <> -1 Then Me.nameTextBox.Text = phoneStreamReader.ReadLine() Me.phoneTextBox.Text = phoneStreamReader.ReadLine() End If

29 11-29 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

30 11-30 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

31 11-31 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

32 11-32 Displaying the Open File Dialog Box Private Sub OpenToolStripMenuItem_Click (ByVal sender As System.Object, ByVal e As System.EventArgs) Handles fileOpenMenuItem.Click 'Open the file Dim responseDialogResult As DialogResult 'Begin in the project folder OpenFileDialog1.InitialDirectory = Application.StartupPath 'Display the Open File dialog box responseDialogResult = OpenFileDialog1.ShowDialog() 'Make sure that the user didn’t click the Cancel button If responseDialogResult <> DialogResult.Cancel Then 'Open the output file phoneStreamWriter = new StreamWriter(OpenFileDialog1.FileName) End If End Sub

33 11-33 Open File to Read Dialog Box Files of Type Determined by Filter Property

34 11-34 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 important to use the keyword IsNot rather than the not equal operator (<>) ' Is the file already open? If phoneStreamWriter IsNot Nothing Then phoneStreamWriter.Close( ) End If

35 11-35 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 Private Sub OpenToolStripMenuItem_Click (ByVal sender As System.Object, ByVal e As System.EventArgs) Handles fileOpenMenuItem.Click 'Open the file Dim responseDialogResult As DialogResult ' Is the file already open? If phoneStreamWriter IsNot Nothing Then phoneStreamWriter.Close( ) End If

36 11-36 Using the Save File Dialog Component In addition to the OpenFileDialog a SaveFileDialog component can be displayed—displays the standard system Save As dialog box The SaveFileDialog allows the user to browse 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

37 11-37 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

38 11-38 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

39 11-39 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

40 11-40 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

41 11-41 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

42 11-42 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


Download ppt "11-1 aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf."

Similar presentations


Ads by Google