480 likes | 618 Views
Chapter 9. Files, Printing, and Structures. 9.1 Introduction. Chapter 9 Topics. Saving data to sequential text files Reading the data back into an application Using the OpenFileDialog, SaveFileDialog, ColorDialog, and FontDialog controls
E N D
Chapter 9 Files, Printing, and Structures
Chapter 9 Topics • Saving data to sequential text files • Reading the data back into an application • Using the OpenFileDialog, SaveFileDialog, ColorDialog, and FontDialog controls • Using the PrintDocument control and how to print reports from your application • Packaging units of data together into structures
9.2Using Files A File Is a Collection of Data Stored on a Computer’s Disk Information Can Be Saved to Files and Later Reused
The Life Span of Data • Thus far, all of our data has been stored in controls and variables existing in RAM • This data disappears once the program stops running • If data is stored in a file on a computer disk, it can be retrieved and used at a later time
Using a File • The file must be opened (If it does not yet exist, it will be created) • Data is read from or written to the file • The program closes the file
Reading and Writing to a File • In writing to a file, data from controls and variables is written into a file - one item after another • In reading from a file, the data is read from the file, in the same order as it was written, back into variables and controls
File Types/Access Methods • File Types • Text files - the data in text files is character based and can be viewed by Notepad • Binary files - the data here is pure binary - same form as exists in RAM • Access Methods • Sequential access - data is written from beginning to end and must be read that way • Random access - data can be read from or written to specific places in the file
Establishing StreamWriter Objects • This establishes ObjectVar as a variable to identify a particular stream of data Dim ObjectVar As System.IO.StreamWriter
Opening a File • Opening a file to begin writing at the beginning • Opening a file to begin writing at the end IOObjectVar = System.IO.File.CreateText(Filename) IOObjectVar = System.IO.File.AppendText(Filename)
More on File Names • Filenames give the path to the file from either a Drive Letter or relative to where the program is stored, examples: "C:\WordProc\memo.txt" "A:\pricelist.txt" "mytext.txt"
Writing Data to a File • Use the WriteLine(Data) method with the established System.IO.Stream variable • Data is converted to text, if it is not already in text format • Each data item is followed by a newline character in the file
Example of Writing to a File Dim studentFile As System.IO.StreamWriter studentFile = System.IO.File.CreateText("StudentData.txt") studentFile.WriteLine("Jim") studentFile.WriteLine(95) studentFile.WriteLine("Karen") studentFile.WriteLine(98) studentFile.WriteLine("Bob") studentFile.WriteLine(82) studentFile.Close() The Resulting File, StudentData.txt Jim 95 Karen 98 Bob 82
Appending to a File • Opening an existing file with "CreateText" results in the contents being deleted and it being rewritten with the new data • Appending to a file, using "AppendText", results in the new data being added to the end of the file: friendFile = System.IO.File.AppendText("A:\MyFriends.txt")
The Write Method ObjectVar.Write(Data) • The write method does not place a newline character after each data item • However, the program must provide some sort of delineation between the data items, such as a blank, so that they are distinguishable for reading
Write Method Example Dim name As String = "Jeffrey Smith" Dim idNum As Integer = 47895 Dim phone As String = "555-7864" outputFile.Write(name) outputFile.Write(" ") outputFile.Write(idNum) outputFile.Write(" ") outputFile.WriteLine(phone) The Resulting File Jeffrey Smith 47895 555-7864
StreamReader Objects • Defining the object and opening the file syntax is similar to writing: • Sample code: Dim ObjectVar As System.IO.StreamReader ObjectVar = System.IO.File.OpenText(Filename) Dim customerFile As System.IO.StreamReader customerFile = System.IO.File.OpenText("customers.txt")
Reading Data from a File • Use the ReadLine method to read the data a line at a time: Dim customerFile As System.IO.StreamReader customerFile = System.IO.File.OpenText("customers.txt") customerName = customerFile.ReadLine()
Determining Whether a File Exists • Use the Exists method, as in If System.IO.File.Exists(filename) Then ' Open the file. inputFile = System.IO.File.OpenText(filename) Else MessageBox.Show(filename & " does not exist.") End If
Detecting the End of a File • The Peek method allows one to examine the next character in the file (without really "reading" it) • If there is not a next character, a value of -1 is returned - indicating that there is no more data - the end of the file has been reached
Code Based on the Peek Method Dim scoresFile As System.IO.StreamReader Dim input As String scoresFile = System.IO.File.OpenText("Scores.txt") Do Until scoresFile.Peek = -1 input = scoresFile.ReadLine() lstResults.Items.Add(input) Loop scoresFile.Close()
Read Method • This method obtains the code of the next character in the file • Use 'Chr' to convert the code into a character
Code Based on the Read Method Dim textFile As System.IO.StreamReader Dim input As String = "" textFile = System.IO.File.OpenText("names.txt") Do While textFile.Peek <> -1 input &= Chr(textFile.Read) Loop textFile.Close()
ReadToEnd Method • This method reads and returns the entire contents of the file, from the current read position
Writing, Then Reading an Entire Array Dim outputFile as System.IO.StreamWriter outputFile = System.IO.File.CreateText("values.txt") For count = 0 To (values.Length – 1) outputFile.WriteLine(values(count)) Next count outputFile.Close() ------------------------------------------------ Dim inputFile as System.IO.StreamReader inputFile = System.IO.File.OpenText("values.txt") For count = 0 To (values.Length – 1) values(count) = Val(inputFile.ReadLine) Next count inputFile.Close()
9.3The OpenFileDialog,SaveFileDialog, FontDialog,and ColorDialog Controls Visual Basic .NET Provides Dialog Controls That Equip Your Applications With Standard Windows Dialog Boxes for Operations Such As Opening Files, Saving Files, and Selecting Fonts and Colors
Displaying an Open Dialog Box ControlName.ShowDialog() • Where ControlName is the name of the OpenFileDialog control • This method returns a value based on the users button push • DialogResult.OK, or • DialogResult.Cancel
Dialog Box Filter Property • The Filter property allows specification of the file types that may be selected: ofdOpenFile.Filter = "Text files (*.txt)|*.txt|" & _ "All Files (*.*)|*.*"
InitialDirectory and Title Property • The InitialDirectory property allows one to specify the default current folder • The Title property allows specification of the text in the title bar, it will replace "Open"
Opening Dialog Box Example ' Configure the Open dialog box and display it. With ofdOpenFile .Filter = "Text files (*.txt)|*.txt|" & _ "All files (*.*)|*.*" .InitialDirectory = "C:\Data" .Title = "Select a File to Open" If .ShowDialog() = DialogResult.OK Then inputFile = System.IO.File.OpenText(.Filename) End If End With
SaveFileDialog Control • SaveFileDialog has the same method • ShowDialog() • The same properties • Filter • InitialDirectory • Title • And the same result constants • DialogResult.OK • DialogResult.Cancel
ColorDialog Control • It resides in the component tray • It is used to select colors, e.g. cdColor.ShowDialog() If cdColor.ShowDialog() = DialogResult.OK Then lblMessage.ForeColor = cdColor.Color End If
FontDialog Control • Similar to the previous ones, but for selecting font characteristics: fdFont.ShowDialog() If fdFont.ShowDialog() = DialogResult.OK Then lblTest.Font = fdFont.Font End If
9.4PrintDocument Control The PrintDocument Control Allows You to Print Data to the Printer
Print Method, PrintPage Event • The Print method initiates the printing process • It triggers a PrintPage event and that event handler actually does the printing PrintDocumentControl.Print()
Code Template for Printing Pages Private Sub pdPrint_PrintPage(ByVal sender As System.Object, _ ByVal e As System.Drawing.Printing.PrintPageEventArgs) _ Handles pdPrint.PrintPage End Sub
DrawString Method • DrawString is used to output text, set the font, and position the text e.Graphics.DrawString(String, _ New Font(FontName, Size, Style), _ Brushes.Black, HPos, VPos)
Specifying Fonts, Sizes, Styles • Fonts are specified with the string which names the font to be used • "Times Roman" • Sizes are specified with a number • 12 • Styles are specified with provided constants • FontStyle.Regular • FontStyle.Bold
Sample Printing Event Procedure Private Sub pdPrint_PrintPage(ByVal sender As System.Object, _ ByVal e As System.Drawing.Printing.PrintPageEventArgs) _ Handles pdPrint.PrintPage Dim inputFile As System.IO.StreamReader Dim x As Integer = 10 Dim y As Integer = 10 inputFile = System.IO.File.OpenText(filename) Do While inputFile.Peek <> -1 e.Graphics.DrawString(inputFile.ReadLine, _ New Font("Courier", 10, FontStyle.Regular), _ Brushes.Black, x, y) y += 12 Loop inputFile.Close() End Sub
String.Format Example String.Format("{0, 10}{1, 10}{2, 10}", 50, "Arg 2", 6) Argument 0 Specifies the argument number Specifies field width for that arg (negative for left justified) Argument 1 Argument 3 Results in the following output: 50 Arg 2 6
9.5Structures Visual Basic .NET Allows You to Create Your Own Data Types, in Which You May Group Multiple Data Fields
Structures vs. Arrays • Arrays: • Multiple fields in one array • All of the same data type • Distinguished by a numerical index • Structures • Multiple fields in one structure • Can be of differing data types • Distinguished by a field name
Syntax for Declaring a Structure • StructureName is a name that identifies the structure itself • FieldDeclarations are the declarations of the individual fields within the structure [AccessSpecifier] Structure StructureName FieldDeclarations End Structure
Structure Declaration Example Structure EmpPayData Dim empNumber As Integer Dim firstName As String Dim lastName As String Dim hours As Single Dim payRate As Decimal Dim grossPay As Decimal End Structure
Creating and Initializing a Structure ' Using the previous declaration Dim deptHead As EmpPayData deptHead.empNumber = 1101 deptHead.firstName = "Joanne" deptHead.lastName = "Smith" deptHead.hours = 40 deptHead.payRate = 25 deptHead.grossPay = deptHead.hours * deptHead.payRate
Passing Structure Variables to Procedures and Functions • Structures can be passed to procedures and functions like any other variable • The data type to use in the specification is the name of the structure
Structures Containing Arrays Structure StudentRecord name As String testScores() As Single End Structure Dim student As StudentRecord ReDim student.TestScores(4) student.name = "Mary McBride" student.testScores(0) = 89 student.testScores(1) = 92 student.testScores(2) = 84 student.testScores(3) = 96 student.testScores(4) = 91
Arrays Containing Structures Dim employees(9) As EmpPayData 'Reusing a Structure ' Refer to the empNumber of the first employee employees(0).empNumber = 1101