Programming with Microsoft Visual Basic .NET Tutorial 9 Sequential Access Files and Printing Lesson A: Sequential Access Files Lesson B: Using a DateTimePicker Control Lesson C: Completing the Carriage House Application At a Glance Instructor’s Notes Overview Outline Objectives Lecture Notes Discussion Topics Extra Projects Key Terms T09-1 Programming with Microsoft Visual Basic .NET Instructor’s Notes Overview You learn about sequential access files and using StreamReader and StreamWriter objects in Tutorial A. Then, Lesson B covers the DateTimePicker Control used for selecting date and/or time. Finally, Lesson C will cover printing. You will complete the Carriage House application in Lessons B and C. NOTE: Visual Basic .NET substantially changes the File handling by using the .NET Stream class. A stream is basically a sequence of bytes. Outline Lecture Topics Pages # Teaching Suggestions in this Manual Sequential Access Files Using a DateTimePicker Control 551-568 572-592 Completing the Carriage House Application 598-604 File Types through The File Application The DateTimePicker Control through System Date and Time Printing a File through The e.Graphics.DrawString method Sequential Access Files Lesson A Objectives: After completing this lesson, you will be able to: Declare StreamReader and StreamWriter object variables Open a sequential access file Determine if a sequential access file exists Write information to a sequential access file Align the text written to a sequential access file Read information from a sequential access file Determine if the computer has finished reading a sequential access file Close a sequential access file T09-2 Programming with Microsoft Visual Basic .NET Lecture Notes File Types Files to which information is written are called output files, because the files store the output produced by an application. Files that are read by the computer are called input files, because an application uses the information in these files as input. There are three types of files in Visual Basic .NET: 1. Sequential access files – data is processed sequentially, that is, from the beginning of the file through to the end. 2. Random access files – data is accessed in a random manner. This topic will be covered in Tutorial 10. 3. Binary access files – Data is read as a stream of bytes from a file and you have to determine how to process the data. Binary access will not be covered. Using a Sequential File A sequential access file is often referred to as a text file, because it is composed of lines of text. You can view it in a text editor, such as Notepad. It might be a list of employees, a memo, or a report. A sequential file is composed of a set of lines with a carriage return and line feed at the end of each line. Sequential access files are similar to cassette tapes in that each line in the file, like each song on a cassette tape, is both stored and retrieved in consecutive order (sequentially). Using StreamWriter and StreamReader Objects In Visual Basic .NET, you use a StreamWriter object to write text to a file – that is a stream of characters or more simply, a stream. You use a StreamReader object to read a stream (a sequence of characters) from a sequential access file. You first declare a variable for the StreamWriter or StreamReader object. You then use an open method which instantiates the object. Opening a Sequential File The OpenText method opens an existing sequential access file for input and allows the computer to read the information stored in the file. If the file does not exist when the OpenText method is processed, the computer displays an error message in a message box. The objects are encapsulated in the System.IO classes of the CLR. You declare the objects with the syntax Accessibility variablename As System.IO.objectType Accessibility is Dim Public or Private. T09-3 Programming with Microsoft Visual Basic .NET To open the file, you use the syntax variableName = System.IO.File.method(filename) To create a file you can use Dim objStreamWriter As New System.IO.StreamWriter objStreamWriter = System.IO.File.CreateText(“pay.txt”) If the file “pay.txt” exists, it will be erased. A new file is then created in the current directory. You can specify a path in the file name part. If you open a file objStreamWriter = System.IO.File.AppendText(“sales.txt”) If the file “sales.txt” exists, it will be opened so that you can append more information at the end of the file. If the file does not exist, it will be created. If you open a file for read as in Dim objStreamReader As New System.IO.StreamReader objStreamReader = System.IO.File.OpenText(“pay.txt”) If you open a file to read that does not exist, an error occurs. NOTE: You do not get an error when using the CreateText or AppendText methods as long as you have permission to access the disk drive. The computer uses a file pointer to keep track of the next character either to read from or to write to a file. When you open a file for input, the computer positions the file pointer at the beginning of the file, immediately before the first character. When you open a file for output, the computer also positions the file pointer at the beginning of the file. When you open a file for append, the computer positions the file pointer immediately after the last character in the file. NOTE: You may find is useful to illustrate file pointers on the board. You also can declare an object variable and open a sequential access file in one statement. For example, you can use the statement Dim objStreamReader As StreamReader = _ System.IO.File.OpenText(“pay.txt”) to declare the objStreamReader variable and open the pay.txt file for input. Determining Whether a File Exists The syntax of the Exists method is System.IO.File.Exists(filename), where filename is the name of the file whose existence you want to verify. The Exists method returns the Boolean value True if filename exists; otherwise, it returns the Boolean value False. T09-4 Programming with Microsoft Visual Basic .NET Writing Information to a Sequential Access File You can use either the Write method or the WriteLine method to write information to a sequential access file. The syntax of the Write method is variablename.Write(data), and the syntax of the WriteLine method is variablename.WriteLine(data). variablename is the name of a StreamWriter object variable, and data is the information you want written to the file associated with the object variable. The difference between the two methods is the location of the file pointer after the data is written to the file. The Write method positions the file pointer at the end of the last character it writes to the file. objStreamWriter.Write(“Good”) objStreamWriter.Write(“ Morning”) Result Good Morning file pointer The WriteLine method, on the other hand, positions the file pointer at the beginning of the next line in the file; it does so by appending a line terminator character, which is simply a carriage return followed by a line feed, to the end of the data. objStreamWriter.WriteLine(“Good”) objStreamWriter.WriteLine(“ Morning”) Result Good Morning file pointer Using the PadLeft and PadRight Methods Many times you may want to manipulate the string data you are writing to a file. The Visual Basic .NET Format function can be used. You can also use the Space(n) function to insert n spaces. This is used to insert a specific number of spaces in textual data. The PadLeft method pads the string on the leftin other words, it inserts the padded characters at the beginning of the string; doing so right-aligns the characters within the string. The PadRight method, on the other hand, pads the string on the right, which inserts the padded characters at the end of the string and left-aligns the characters within the string. NOTE: The size of a space is dependant on the Font being used. To use Space(n) effectively, you may want to use a fixed-width font, such as Courier. You can use the PadLeft and PadRight methods to pad a string with a character until the string is a specified length. The syntax is stringvariable.PadLeft(length[, character]) stringvariable.PadRight(length[, character]) stringvariable is the name of the String variable that contains the string you want to pad. T09-5 Programming with Microsoft Visual Basic .NET Length is an integer that represents the desired length of the string—in other words, the total number of characters you want the string to contain. The character argument is the character that each method uses to pad the string until it reaches the desired length. NOTE: The character arguments are optional in the syntax; if omitted, the default character is the space character. For example, to right justify a number, you can use the ToString method to convert the number to a string. Dim intNum as Integer = 42, strNum As String strNum = intNum.ToString.PadLeft(5) Results in: “ 42” (three spaces and the string “42”) To align a column of numbers by the decimal point: 1. Use the Format function to ensure that each number in the column has the same number of digits to the right of the decimal point. 2. Use the PadLeft method to pad the number with spaces; this right-aligns the number within the column. Because each number has the same number of digits to the right of the decimal point, aligning each number on the right will, in effect, align each by their decimal point. Reading Information from a Sequential Access File The ReadLine method will read a line of text from a sequential access file. A line is defined as a sequence of characters followed by the line terminator character. The string returned by the ReadLine method contains only the characters contained in the line. It does not include the line terminator character. The syntax of the ReadLine method is variablename.ReadLine(), where variablename is the name of a StreamReader object variable. You can read one line at a time by using a repetition structure along with the Peek method. When the Peek method returns -1, there are no more characters in the file to read. Finally, when you are finished with reading or writing a file, you should close the file with the Close method. NOTE: There is also a Read method that will read one character at a time from the file. However, this is not a commonly used and is not covered in this book. Closing a Sequential Access File To prevent the loss of data, you should use the Close method to close a sequential access file as soon as you are finished using it. The syntax of the Close method is variablename.Close(), where variablename is the name of either a StreamReader or StreamWriter object variable. T09-6 Programming with Microsoft Visual Basic .NET The File Application On your computer’s hard disk is an application that allows you to save information to and read information from a sequential access file. Using a DateTimePicker Control Lesson B Objectives: After completing this lesson, you will be able to: Add a DateTimePicker control to a form Control the appearance of a DateTimePicker control Format the text that appears in the DateTimePicker control Set and retrieve the information stored in a DateTimePicker control Retrieve the system date and time Display a form immediately Completing the Carriage House Application’s User Interface Many times, you need to allow the user to input a date and time for something. For example, you might be scheduling a movie viewing. You will need both the date and time. The DateTimePicker control in Visual Basic .NET is a convenient and intuitive way for the user to select a date and time. You will also need to learn how to use the system date and time. Adding a DateTimePicker Control to a Form The DateTimePicker control allows the user to select either a date or time, and then it displays the selected information in a specified format. NOTE: If you have not used the DataTimePicker control before, you may need to practice. It has not changed from the VB 6 version. Open the VBNET\Tut09\Carriage solution: Illustrate the use of the DateTimePicker by adding to a form. Show how the Format property affects what is displayed by displaying each of the four Format types. Run the simple app and click on the down arrow. Note what is displayed each time the calendar is clicked. Click on the Year in the display. An UpDown appears that can be used to scroll through years. Show how you can scroll each portion of the date using the arrow keys. T09-7 Programming with Microsoft Visual Basic .NET Change the ShowUpDown property to True and further illustrate how the arrow keys change values. Change the Format to show Time. Mention that the ShowUpDown is most commonly used for time. To show both date and time, you have to use Custom format. Following are the format to create a custom format. NOTE: A small m for minute, capital M for month. That is, in this instance, capitalization is important. String Description D The one- or two-digit day. Dd The two-digit day. Single digit day values are preceded by a zero. Ddd The three-character day-of-week abbreviation. Dddd The full day-of-week name. H The one- or two-digit hour in 12-hour format. Hh The two-digit hour in 12-hour format. Single digit values are preceded by a zero. H The one- or two-digit hour in 24-hour format. HH The two-digit hour in 24-hour format. Single digit values are preceded by a zero. M The one- or two-digit minute. Mm The two-digit minute. Single digit values are preceded by a zero. M The one- or two-digit month number. MM The two-digit month number. Single digit values are preceded by a zero. MMM The three-character month abbreviation. MMMM The full month name. S The one- or two- digit seconds. Ss The two-digit seconds. Single digit values are proceeded by a zero. T The one-letter AM/PM abbreviation (that is, "AM" is displayed as "A"). Tt The two-letter AM/PM abbreviation (that is, "AM" is displayed as "AM"). T09-8 Programming with Microsoft Visual Basic .NET The ShowUpDown Property The DateTimePicker control’s ShowUpDown property determines whether a list arrow button or up and down arrow buttons appear on the control. If the property is set to its default value, False, the control contains a list arrow button. If, on the other hand, the ShowUpDown property is set to True, up and down arrow buttons appear on the control. The Format Property You can use the Format property to control the format (style) of the date or time displayed in the DateTimePicker control. Figure 9-27 lists the valid settings for the Format property and describes the purpose of each setting. The figure also includes examples of dates and times formatted using each setting. Format Method None ToLongDateString ToShortDateString ToLongTimeString ToShortTimeString Results MM/DD/YYYY H:mm:SS AM Day, Month Day, Year MM/DD/YYYY h:mm:ss tt h:mm tt You can also retrieve individual components of the date/time. The DayOfWeek returns an integer reflecting the day relative to Sunday, which is zero. If you want the word, you then use the ToString method. The Value Property When you add a DateTimePicker control to a form, Visual Basic .NET retrieves the current data and time from your computer system’s clock, and assigns both values to the DateTimePicker control’s Value property. You can verify that fact by viewing the Value property in the Properties list. A DateTime object is simply an object that represents a date and an optional time. To use the DataTime object, you create a date by specifying, in this sequence, year, month, day, and optionally, hour, minute, second. Hour is a 24 hour format. Hours after noon must add 12 to the hour normally used. Retrieving the Information Stored in the Value Property The ToLongDateString method returns the date formatted using the Long format (dddd,MMMM dd, yyyy), and the ToShortDateString method returns the date formatted using the Short format (M/d/yyyy). The ToLongTimeString method returns the time formatted using the Long format (h:mm:ss tt), and the ToShortTimeString method returns the time formatted using the Short format (h:mm tt). T09-9 Programming with Microsoft Visual Basic .NET The Text Property The text that appears in a DateTimePicker control is stored in the control’s Text property. Visual Basic .NET automatically assigns to the Text property the contents of the Value property formatted using the setting specified in the Format property; this is illustrated in Figure 9-31. Retrieving the System Date and Time The system date is the current date according to your computer system’s clock. You can retrieve the system date using the syntax Today[.methodname], where methodname (which is optional) is ToLongDateString, ToShortDateString, or ToString(formatting characters). The system time is the current time according to your computer system’s clock. You can retrieve the system time using the syntax TimeOfDay[.methodname], where methodname (which is optional) is ToLongTimeString, ToShortTimeString, or ToString (formatting characters). Hands-On Coding the EventForm Load Event Coding the CarriageForm load event procedure and the AddButton click event procedure Completing the Carriage House Application Lesson C Objectives: After completing this lesson, you will be able to: Add a PrintDocument control to a form Print text using the Print and e.Graphics.DrawString methods Code a PrintDocument control’s PrintPage event procedure Adding a PrintDocument Control to the Form NOTE: Printing is totally redone for Visual Basic .NET – much for the better. It is now actually easy to create a report. People still want to see printed material. In Visual Basic .NET, the PrintDocument object provides the underlying techniques for printing. To learn how to print a document: The PrintDocument control allows you easy access to Visual Basic .NET printing capability The e.Graphics.DrawString method allows you to Print text T09-10 Programming with Microsoft Visual Basic .NET The PrintPage event occurs when you execute the PrintDocument.Print method Coding the Print Report Button’s Click Event procedure Figure 9-45 shows the pseudocode for the Print Report button’s Click event procedure, which is responsible for using the ReportPrintDocument control to print the contents of the events.txt sequential access file. The Print method causes the PrintDocument control’s PrintPage event to occur. You use the PrintPage event to indicate the information you want to print, as well as how you want the information to appear in the printout. The Windows Forms PrintDocument component is used to set the properties that describe what to print and then to print the document within Windows applications. It can be used in conjunction with the PrintDialog control to be in command of all aspects of document printing. Two of the main scenarios that involve the PrintDocument component are: Simple print jobs, such as printing an individual text file. In such a case you would add the PrintDocument component to a Windows Form, then add programming logic that prints a file in the PrintPage event handler. The programming logic should culminate with the Print method to print the document. This method sends a Graphics object, contained in the Graphics property of the PrintPageEventsArgs class, to the printer. More complex print jobs, such as a situation where you will want to reuse printing logic you have written. In such a case you would derive a new component from the PrintDocument component and override the PrintPage event. Coding the PrintPage Event Procedure The PrintPage event procedure should print the contents of the events.txt file in a report format. The report should contain a report header, which describes the contents of the report, and three columns of information. The first column should list the event names, the second column the event dates, and the third column the event prices. The process to print a file is to: 1. Declare a StreamReader object and verify the file exists using System.IO.FileExists(“filename”) 2. Use the PrintDocument.Print() to cause the PrintPage event to be called. 3. In the PrintPage event, you format the text you want to print and use the DrawString method of the Graphics object to actually print the text. To use the DrawString method you: 1. Format the data you want to print 2. Set the coordinates where you want to print the formatted data 3. Call the e.Graphics.DrawString method T09-11 Programming with Microsoft Visual Basic .NET The e.Graphics.DrawString Method You use the e.Graphics.DrawString method to print text on the printer. NOTE: The Graphics class provides methods for drawing lines, curves, figures, images, and text. A Graphics object stores attributes of the display device and attributes of the items to be drawn. This replaces many graphic methods from VB6. For the DrawString method, you specify the Font, and location NOTE: Be sure to emphasize the different types of fonts and how to use them. It may be useful to illustrate in a word processor. Fonts are: Fixed-spaced – Uses the same amount of space for each character Proportional – Prints each letter in the space needed to print the character. The letter “W” takes more space to print than the letter “I” In many situations, it is easier to use a fixed-space font, such as Courier New to align the printed data. With some daring calculations, you can set the horizontal and vertical location for any text and print using any font. That is beyond the scope of this tutorial. Hands-on Complete the Special Event Report Continuing the VBNET\Tut09\Carriage solution, you will add a PrintDocument control to the component tray, code the Print Report Button’s click event procedure, and then code the PrintPage event procedure. Discussion Topics 1. 2. 3. 4. What are the advantages and disadvantages of sequential data files? What are the advantages and disadvantages of the DateTimePicker control? What are the advantages of the PrintDocument component? What is the difference between Write and WriteLine methods? Extra Projects Write a program that will read the Carriage.vb program and display the lines in a list box control. Key Terms Sequential Access File – A sequential access file must be accessed in sequential order. StreamReader – A class that allows for the reading of a sequential file T09-12 Programming with Microsoft Visual Basic .NET StreamWriter – A Class that allows for the creating or updating of a sequential file Solutions to Exercises can be found within the Instructor’s Resource Kit (CD-ROM) that accompanies this text or at the following link: http://www.course.com T09-13 Programming with Microsoft Visual Basic .NET Solutions to Exercises can be found within the Instructor’s Resource Kit (CD-ROM) that accompanies this text or at the following link: http://www.course.com T09-14