© copyright 1992-2004 by deitel & associates, inc. and pearson education inc. all rights...
TRANSCRIPT
1
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
Outline
24.1 Test-Driving the Ticket Information Application24.2 Data Hierarchy24.3 Files and Streams24.4 Writing to a File: Creating the Write Event Application24.5 Building the Ticket Information Application24.6 Wrap-Up
Tutorial 24 – Ticket Information Application
Introducing Sequential-Access Files
2
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
Objectives
• In this tutorial, you will learn to:– Create, read from, write to and update files.
– Understand a computer’s data hierarchy.
– Become familiar with sequential-access file processing.
– Use StreamReader and StreamWriter classes to read from, and write to, sequential-access files.
– Add and configure a MonthCalendar control.
3
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
24.1 Test Driving the Ticket Information Application
Application Requirements A local town has asked you to write an application that allows its residents to view community events for the current month. Events taking place in the town include concerts, sporting events, movies and other forms of entertainment. When the user selects a date, the application must indicate whether there are events scheduled for that day. The application must list the scheduled events and allow the user to select a listed event. When the user selects an event, the application must display the time and price of the event and a brief description of the event. The community event information is stored in a sequential-access file named calendar.txt.
4
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
24.1 Test Driving the Ticket Information Application
Figure 24.1 Ticket Information application’s GUI.
Arrow buttons allow user to scroll through months
MonthCalendar control
ComboBox lists any events
TextBox displays event details
5
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
24.1 Test Driving the Ticket Information Application
18th day of the month selected
No events displayed
19th day of the month selected
Event information displayed
Figure 24.2 Ticket Information application displaying event information.
6
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
24.2 Data Hierarchy
• Data– Data has many forms, such as letters– Letters, numbers, and some special symbols are characters
– The set of all characters that represent data is known as the character set
– Data is broken down by a computer into bits, or binary digits
– Binary digits can either be 1 or 0
– Visual Basic .NET uses Unicode characters, which means every character is 2 bytes (16 bits)
– Fields are composed of characters– Records are groups of related fields– Files are groups of related records
7
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
24.2 Data Hierarchy
• Data (continued)– Record keys distinguish a given record from all other
records– Records are often stored in order of their record keys in a file
known as a sequential file
– Related files are often stored in databases
– Databases are managed by programs in a database management system (DBMS)
8
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
24.2 Data HierarchyFigure 24.3 Data hierarchy.
Sally
Tom
Judy
Iris
Randy
Black
Blue
Green
Orange
Red
Judy Green
J u d y Field
01001010
Byte (character J
(character J )
1 Bit
Record
File
9
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
24.3 Files and Streams
0 1 2 3 4 5 6 7 8 9 n-1...
... end-of-file marker
Figure 24.4 Visual Basic .NET’s conceptual view of an n-byte file.
10
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
24.4 Writing to a File: Creating the Write Event Application
• Adding a dialog to open or create a file– Select OpenFileDialog in the Windows Forms tab of the
Toolbox
– The property FileName is the file the application reads information from
– If CheckFileExists is False, the user is allowed to specify a file name
– A new file is created and opened if a user specifies a file name that does not exist
11
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
24.4 Writing to a File: Creating the Write Event Application
OpenFileDialog control
Figure 24.5 OpenFileDialog added and renamed.
12
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
24.4 Writing to a File: Creating the Write Event Application
• Determining if a file name is valid– Method CheckValidity receives a file name and returns True if it is valid
– Method EndsWith receives a filename and returns True if it ends with a .txt extension
– If the file name is valid, the Enter and Close File Buttons will be enabled
13
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
24.4 Writing to a File: Creating the Write Event Application
CheckValidity Function procedure
header
Figure 24.6 Method CheckValidity header.
14
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
24.4 Writing to a File: Creating the Write Event Application
Displaying error message if incorrect file type is provided
Figure 24.7 Displaying an error message indicating an invalid file name.
15
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
24.4 Writing to a File: Creating the Write Event Application
Figure 24.8 Changing the GUI’s appearance if a valid file name is entered.
Enabling and disabling Buttons
16
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
24.4 Writing to a File: Creating the Write Event Application
• StreamWriter– Used to create objects for writing text to a file– DialogResult determines if Cancel Button was clicked
and the method should therefore exit. – StreamWriter takes two arguments
• Name of the file to write to
• A Boolean value to determine if StreamWriter will append information on the end of the file
17
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
24.4 Writing to a File: Creating the Write Event Application
Figure 24.9 System.IO namespace imported into FrmWriteEvent class.
Importing namespace System.IO
18
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
24.4 Writing to a File: Creating the Write Event Application
Figure 24.10 Declaring a StreamWriter object.
Declaring StreamWriter
19
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
24.4 Writing to a File: Creating the Write Event Application
Figure 24.11 Write Event application Form in design view.
Open File… Button
20
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
24.4 Writing to a File: Creating the Write Event Application
Figure 24.12 Displaying the Open dialog and retrieving the result.
Displaying Open dialog
If the user clicks Cancel the event handler exits
Setting variable to user-specified file name
21
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
24.4 Writing to a File: Creating the Write Event Application
Figure 24.13 Validating the file name and initializing a StreamWriter object.
Check for valid file name
Create StreamWriter object
22
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
24.4 Writing to a File: Creating the Write Event Application
Figure 24.14 Clearing user input.
Clearing user input
23
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
24.4 Writing to a File: Creating the Write Event Application
Figure 24.15 StreamWriter writing to a file.
Writing information to file
24
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
24.4 Writing to a File: Creating the Write Event Application
Figure 24.16 Closing the StreamWriter.
Closing StreamWriter object
25
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
24.4 Writing to a File: Creating the Write Event Application
Figure 24.17 Write Event application executing.
26
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
24.4 Writing to a File: Creating the Write Event Application
Figure 24.18 Open dialog displaying contents of the template Ticket Information application’s bin folder.
27
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
24.4 Writing to a File: Creating the Write Event Application
Figure 24.19 Sequential-access file generated by Write Event application.
Day and time of event, ticket price,
event name and description
Outline28
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
1 Imports System.IO
2
3 Public Class FrmWriteEvent
4 Inherits System.Windows.Forms.Form
5
6 Private m_objOutput As StreamWriter
7
8 ' Windows Form Designer generated code
9
10 ' determine validity of file type
11 Private Function CheckValidity(ByVal strName As String) _
12 As Boolean
13
14 ' show error if user specified invalid file
15 If strName.EndsWith(".txt") = False Then
16 MessageBox.Show("File name must end with .txt", _
17 "Invalid File Type", _
18 MessageBoxButtons.OK, MessageBoxIcon.Error)
19 Return False ' to indicate invalid file type
20
WriteEvent.vb(1 of 4)
Importing a namespace System.IO
StreamWriter that will write text to a file
Outline29
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
21 ' change status of Buttons if file name is valid
22 Else
23 btnOpenFile.Enabled = False
24 btnEnter.Enabled = True
25 btnCloseFile.Enabled = True
26 Return True ' to indicate text file specified
27 End If
28
29 End Function ' CheckValidity
30
31 ' handles Open File... Button’s Click event
32 Private Sub btnOpenFile_Click(ByVal sender As System.Object, _
33 ByVal e As System.EventArgs) Handles btnOpenFile.Click
34
35 ' display Open dialog
36 Dim result As DialogResult = objOpenFileDialog.ShowDialog
37
38 ' exit event handler if user clicked Cancel Button
39 If result = DialogResult.Cancel Then
40 Return
41 End If
42
43 ' get specified filename
44 Dim strFileName As String = objOpenFileDialog.FileName
45
WriteEvent.vb(2 of 4)
Retrieve user input from Open dialog
Storing filename entered by user
Outline30
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
46 ' show error if user specified invalid file
47 If CheckValidity(strFileName) = True Then
48
49 ' append data to file via StreamWriter
50 m_objOutput = New StreamWriter(strFileName, True)
51 End If
52
53 End Sub ' btnOpenFile_Click
54
55 ' clear TextBoxes and reset NumericUpDown control
56 Private Sub ClearUserInput()
57 updDay.Value = 1
58 txtPrice.Clear()
59 txtEvent.Clear()
60 txtDescription.Clear()
61 End Sub ' ClearUserInput
62
63 ' handles Enter Button’s Click event
64 Private Sub btnEnter_Click(ByVal sender As System.Object, _
65 ByVal e As System.EventArgs) Handles btnEnter.Click
66
WriteEvent.vb(3 of 4)
Create StreamWriter object to associate a stream with the user-specified text file
Outline31
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
67 ' using StreamWriter to write data to file
68 m_objOutput.WriteLine(updDay.Text)
69 m_objOutput.WriteLine(dtpTime.Text)
70 m_objOutput.WriteLine(txtPrice.Text)
71 m_objOutput.WriteLine(txtEvent.Text)
72 m_objOutput.WriteLine(txtDescription.Text)
73 ClearUserInput() ' prepare GUI for more user input
74 End Sub ' btnEnter_Click
75
76 ' handles Close File Button’s Click event
77 Private Sub btnCloseFile_Click(ByVal sender As System.Object, _
78 ByVal e As System.EventArgs) Handles btnCloseFile.Click
79
80 m_objOutput.Close() ' close StreamWriter
81
82 ' allow user to open another file
83 btnOpenFile.Enabled = True
84 btnEnter.Enabled = False
85 btnCloseFile.Enabled = False
86 End Sub ' btnCloseFile_Click
87
88 End Class ' FrmWriteEvent
WriteEvent.vb(4 of 4)
Append data to end of file
Closing the file’s associated stream
32
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
24.5 Building the Ticket Information Application
Action Control Event/Method Label the application’s controls lblDay,
lblTime, lblPrice, lblEvent, lblDescription
Application is run
FrmEvents Load
Display the current day’s events
mvwDate DateChanged
Display the selected day’s events
cboEvent SelectedIndexChanged
Retrieve index of selected item in the Pick an event: ComboBox
cboEvent
Display event information in the Description: TextBox
txtDescription
CreateEventList
Extract data for the current day
Clear the Pick an event: ComboBox cboEvent
Figure 24.21 ACE table for the Ticket Information application.
33
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
24.5 Building the Ticket Information Application
Action Control Event/Method If events are scheduled for that day Add each event to the Pick an event: ComboBox
cboEvent, m_strData
DIsplay "- Events -" in the Pick an event: ComboBox
cboEvent
Display "No events today." in the Description: TextBox
txtDescription
Else DIsplay "- No Events -" in the Pick an event: ComboBox
cboEvent
Display "No events today." in the Description: TextBox
txtDescription
ExtractData
Retrieve the selected date from the calendar
mvwDate
Open calendar.txt file for reading objInput
Read the first line of the file objInput
Figure 24.21 ACE table for the Ticket Information application.
34
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
24.5 Building the Ticket Information Application
Action Control Event/Method While there are events left in the file and the number of events is less than 10
objInput
If the current event is for the day selected by the user Store the event information
m_strData, strLine, objInput
Increment the number of events for the selected day
Else Move to the beginning of the next record in the file
objInput
Read the next line of the file objInput
Figure 24.21 ACE table for the Ticket Information application.
35
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
24.5 Building the Ticket Information Application
Figure 24.22 MonthCalendar template application’s Form.
36
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
24.5 Building the Ticket Information Application
Figure 24.23 System.IO namespace imported to FrmEvents.
37
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
24.5 Building the Ticket Information Application
• Building the Ticket Information application– Array m_strData stores the event information read from
the file– m_intNumberOfEvents stores the number of events for a
given day
38
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
24.5 Building the Ticket Information Application
Figure 24.24 Instance variables declared in the Ticket Information application.
Creating an array of Strings
39
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
24.5 Building the Ticket Information Application
Figure 24.25 Load event handler calling method CreateEventList.
You will add code to CreateEventList later
40
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
24.5 Building the Ticket Information Application
Figure 24.26 MonthCalendar’s DateChanged event handler.
Calling the CreateEventList
method
41
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
24.5 Building the Ticket Information Application
• CreateEventList– ExtractData is passed the selected date to do two actions
• Store event information in array m_strData• assign the number of events scheduled for the specified date to m_intNumberOfEvents
– Informs user whether there are events scheduled for a given day
42
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
24.5 Building the Ticket Information Application
Figure 24.27 CreateEventList modified to call method ExtractData and clear the ComboBox.
You will add code to ExtractData in the
next box
43
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
24.5 Building the Ticket Information Application
Figure 24.28 Displaying the events scheduled for the specified day.
Extracting event name from array and displaying it in the
ComboBox
Indicating that events are scheduled
for the day
Indicating that no events are scheduled
for the day
44
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
24.5 Building the Ticket Information Application
• ExtractData used to read from a sequential file– A Do While…Loop is used to ensure that there are still
characters on the file– For every entry in the file, the date is read by StreamReader and then converted to the Integer intFileDay
– If the date read from the file is the same as the specified date, then the rest of the event information will be read
45
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
24.5 Building the Ticket Information Application
Figure 24.29 ExtractData method’s variable declarations.
46
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
24.5 Building the Ticket Information Application
Figure 24.30 Using StreamReader to read data from a sequential-access file.
Creating a StreamReader
object to read the calendar.txt file
47
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
24.5 Building the Ticket Information Application
Figure 24.31 Extracting the day from an event entry in the file.
Verify that end of file has not been reached
and less than 10 events are stored in the array
48
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
24.5 Building the Ticket Information Application
Figure 24.32 Sequentially reading event entries from the file.
Store event information in a row of the array
49
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
24.5 Building the Ticket Information Application
Figure 24.33 cboEvent_SelectedIndexChanged defined to display event information.
Displaying event information
in the TextBox.
Outline50
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
1 Imports System.IO
2
3 Public Class FrmEvents
4 Inherits System.Windows.Forms.Form
5
6 ' stores information for up to 10 events
7 Private m_strData As String(,) = New String(9, 4) {}
8
9 ' number of events on a given day
10 Private m_intNumberOfEvents As Integer
11
12 ' Windows Form Designer generated code
13
14 ' populates ComboBox with current day’s events (if any)
15 Private Sub CreateEventList()
16
17 Dim intCount As Integer ' counter
18
19 ' stores event information in array m_strData
20 ' and assigns number of events to m_intNumberOfEvents
21 ExtractData(mvwDate.SelectionStart)
22
23 ' remove any items in ComboBox
24 cboEvent.Items.Clear()
25
TicketInformation-.vb(1 of 6)
Importing namespace System.IO
Outline51
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
TicketInformation-.vb(2 of 6)
26 ' add each new event name to ComboBox
27 If m_intNumberOfEvents > 0 Then
28
29 For intCount = 0 To m_intNumberOfEvents - 1
30
31 ' extract and display event name
32 cboEvent.Items.Add(m_strData(intCount, 3))
33 Next
34
35 ' inform user that events are scheduled
36 cboEvent.Text = " - Events - "
37 txtDescription.Text = "Pick an event."
38
39 ' inform user that no events are scheduled
40 Else
41 cboEvent.Text = " - No Events - "
42 txtDescription.Text = "No events today."
43 End If
44
45 End Sub ' CreateEventList
46
47 ' extracts event data for a specified day from calendar.txt
48 ' and returns number of events during that day
49 Private Sub ExtractData(ByVal dtmDay As Date)
50
Outline52
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
51 ' set to selected date in MonthCalendar control
52 Dim intChosenDay As Integer = dtmDay.Day
53 Dim intFileDay As Integer ' day of event from file
54 Dim intLineNumbers As Integer ' counts lines to skip
55
56 m_intNumberOfEvents = 0 ' set number of events to 0
57
58 ' initialize StreamReader to read lines from file
59 Dim objInput As StreamReader = New StreamReader("calendar.txt")
60
61 ' read first line before entering loop
62 Dim strLine As String = objInput.ReadLine
63
64 ' loop through lines in file
65 Do While objInput.Peek > -1 AndAlso m_intNumberOfEvents < 10
66
67 intFileDay = Convert.ToInt32(strLine) ' extract day
68
TicketInformation-.vb(3 of 6)
Creating StreamReader object
Using method ReadLine to read the first line of the file
Ensuring that the end of the file has not been reached
Outline53
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
69 ' if event scheduled for specified day, store information
70 If intFileDay = intChosenDay Then
71 m_strData(m_intNumberOfEvents, 0) = strLine
72 m_strData(m_intNumberOfEvents, 1) = objInput.ReadLine
73 m_strData(m_intNumberOfEvents, 2) = objInput.ReadLine
74 m_strData(m_intNumberOfEvents, 3) = objInput.ReadLine
75 m_strData(m_intNumberOfEvents, 4) = objInput.ReadLine
76 m_intNumberOfEvents += 1
77 Else
78
79 ' skip to next event in file
80 For intLineNumbers = 0 To 3
81 strLine = objInput.ReadLine
82 Next
83
84 End If
85
86 ' read day of next event in file
87 strLine = objInput.ReadLine
88 Loop ' End Do While
89
90 End Sub ' ExtractData
TicketInformation-.vb(4 of 6)
Reading information from a file and storing the data in an array
Using method ReadLine to skip to the next event in the file
Using method ReadLine to read the day of the next event
Outline54
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
91
92 ' handles Form’s Load event
93 Private Sub FrmEvents_Load(ByVal sender As System.Object, _
94 ByVal e As System.EventArgs) Handles MyBase.Load
95
96 ' display any events scheduled for today in ComboBox
97 CreateEventList()
98 End Sub ' FrmEvents_Load
99
100 ' handles MonthCalendar’s DateChanged event
101 Private Sub mvwDate_DateChanged(ByVal sender As System.Object, _
102 ByVal e As System.Windows.Forms.DateRangeEventArgs) _
103 Handles mvwDate.DateChanged
104
105 ' display any events for the specified date in ComboBox
106 CreateEventList()
107 End Sub ' mvwDate_DateChanged
108
109 ' handles ComboBox’s SelectedIndexChanged event
110 Private Sub cboEvent_SelectedIndexChanged(ByVal sender As _
111 System.Object, ByVal e As System.EventArgs) _
112 Handles cboEvent.SelectedIndexChanged
TicketInformation-.vb(5 of 6)
Outline55
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
113
114 ' place time, price and description of event in TextBox
115 txtDescription.Text = m_strData(cboEvent.SelectedIndex, 1)
116 txtDescription.Text &= ControlChars.CrLf
117 txtDescription.Text &= "Price: $" & _
118 m_strData(cboEvent.SelectedIndex, 2)
119 txtDescription.Text &= ControlChars.CrLf
120 txtDescription.Text &= m_strData(cboEvent.SelectedIndex, 4)
121 End Sub ' cboEvent_SelectedIndexChanged
122
123 End Class ' FrmEvents
TicketInformation-.vb(6 of 6)