Upload
jeremy-lawson
View
215
Download
0
Embed Size (px)
Citation preview
T U T O R I A L
2009 Pearson Education, Inc. All rights reserved.
1
23Ticket Information
ApplicationIntroducing
Sequential-Access Files
2009 Pearson Education, Inc. All rights reserved.
2
Outline
23.1 Test-Driving the Ticket Information Application
23.2 Data Hierarchy
23.3 Files and Streams
23.4 Writing to a File—Creating the Write Event Application
23.5 Building the Ticket Information Application
23.6 Using LINQ and Class File to ExtractData from a Text File
2009 Pearson Education, Inc. All rights reserved.
3
In this tutorial you will learn: ■ 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.■ Use the OpenFileDialog component.■ Add and configure a MonthCalendar control.■ Use LINQ to query a sequential-access file.
Objectives
2009 Pearson Education, Inc. All rights reserved.
4
■ A file is a collection of data that is given a name, such as data.txt or Welcome.sln.
■ Data in files exists even after the application that created the data terminates—such data is called persistent data.
■ Sequential-access files contain information that is read from a file in the order in which it was originally written to the file.
■ This application allows the user to create or open a text file with information.
Introduction
Application Requirements
2009 Pearson Education, Inc. All rights reserved.
5
23.1 Test-Driving the Ticket Information Application
A local town has asked you to write an application that allows its residents to view community events for the current month. 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 one. When the user selects an event, the application must display its time and price and a brief description of the event. The community-event information is stored in a sequential-access file named calendar.txt.
2009 Pearson Education, Inc. All rights reserved.
6
■ Run the completed Ticket Information application (Fig. 23.1).
■ The MonthCalendar control should show theday and month on which you actually run the application.
Test-Driving the Ticket Information Application
Figure 23.1 | Ticket Information application’s GUI.
Arrow buttons allow userto scroll through months
MonthCalendar control
ComboBox lists any events
TextBox displays event details
2009 Pearson Education, Inc. All rights reserved.
7
■ Select the 13th in the MonthCalendar. Note that the ComboBox displays "- No Events -" (Fig. 23.2).
■ Select the 19th. Click the ComboBox to view the scheduled events, then select an event to view its information.
Test-Driving the Ticket InformationApplication (Cont.)
Figure 23.2 | Ticket Information application displaying event information.
13th day of the month selected
No events displayed
19th day of the month
selected
Event information
displayed
2009 Pearson Education, Inc. All rights reserved.
8
■ Data items processed by computers form a data hierarchy (Fig. 23.3).
■ Digits, letters and special symbols are referred to as characters.
■ The set of all characters representing data items on a particular computer is called that computer’s character set.
23.2 Data Hierarchy
2009 Pearson Education, Inc. All rights reserved.
9
Figure 23.3 | Data hierarchy.
23.2 Data Hierarchy (Cont.)
2009 Pearson Education, Inc. All rights reserved.
10
■ The smallest data item is called a bit—a digit that can hold only 0 or 1.
■ Computer circuitry performs various simple bit manipulations such as:
– examining the value of a bit
– setting the value of a bit
– reversing the value of a bit
■ Bytes are composed of eight bits.
■ Characters in Visual Basic are Unicode characters, which are composed of two bytes.
23.2 Data Hierarchy (Cont.)
2009 Pearson Education, Inc. All rights reserved.
11
■ Fields are composed of characters and convey meaningful information.
■ A record is a collection of several related fields.– A payroll system, for example, would have a record for
each employee, with several information fields.
■ A group of related records is stored in a file. A payroll file for a company might contain thousands of employee records.
23.2 Data Hierarchy (Cont.)
2009 Pearson Education, Inc. All rights reserved.
12
■ A record key identifies a record as belonging to a particular person or entity.
– The record key must be unique.
– In the payroll record just described, the employee identification number normally would be chosen as the record key.
■ The most common type of organization is called a sequential-access file, in which records are stored in order.
■ Sometimes a group of related files is called a database.
23.2 Data Hierarchy (Cont.)
2009 Pearson Education, Inc. All rights reserved.
13
■ Files are viewed as sequential streams of bytes (Fig. 23.4).
■ When a file is opened, Visual Basic creates an object and associates a stream with that object:
– StreamReader takes text input from a file.
– StreamWriter outputs text to a file.
23.3 Files and Streams
Figure 23.4 | Visual Basic’s conceptual view of an n-byte file.
2009 Pearson Education, Inc. All rights reserved.
14
Common Programming Error
Attempting to open a file from multiple programs at once (or even the same program) is a logic error. A file can be opened by only one program at a time.
2009 Pearson Education, Inc. All rights reserved.
15
■ Open the WriteEvent template application (Fig. 23.5).
■ Add an OpenFileDialog component from the All Windows Forms category of the Toolbox.
■ Name it openFileDialog, and change its FileName property to calendar.txt.
■ Set property CheckFileExists to False so that if the user specifies a nonexistent file, that file is created.
Adding a Dialog to Open or Create a File
2009 Pearson Education, Inc. All rights reserved.
16
Figure 23.5 | openFileDialog added and renamed.
OpenFileDialog component
Adding a Dialog to Open or Create a File (Cont.)
2009 Pearson Education, Inc. All rights reserved.
17
Determining Whether a File Name Is Valid
■ Method CheckValidity (Fig. 23.6) receives a file name as a String.
■ If the file name is valid, the Function returns True.
Figure 23.6 | Method CheckValidity header.
CheckValidity Function procedure header
2009 Pearson Education, Inc. All rights reserved.
18
Determining Whether a File Name Is Valid (Cont.)
■ String method EndsWith (Fig. 23.7) returns False if the value of variable name does not end with .txt.
■ In this case, a MessageBox is displayed, informing the user that the application expects a text file.
Figure 23.7 | Displaying an error message indicating an invalid file name.
Displaying error message if incorrect file type is provided
2009 Pearson Education, Inc. All rights reserved.
19
Determining Whether a File Name Is Valid (Cont.)
■ After the user enters a file name, line 13 (Fig. 23.8) disables the Open File... Button.
■ Lines 14–15 enable the Enter and Close File Buttons.
Figure 23.8 | Changing the GUI if a valid file name is entered.
Enabling and disabling Buttons
2009 Pearson Education, Inc. All rights reserved.
20
Creating a StreamWriter Object
■ To access the classes that enable you to perform file processing, import namespace System.IO (Fig. 23.9).
Figure 23.9 | System.IO namespace imported into class WriteEventForm.
Importing namespace System.IO
2009 Pearson Education, Inc. All rights reserved.
21
Creating a StreamWriter Object (Cont.)
■ Namespace System.IO includes class StreamWriter, which is used to create objects for writing text to a file (Fig. 23.10).
Figure 23.10 | Declaring a StreamWriter variable.
Declaring StreamWriter variable
2009 Pearson Education, Inc. All rights reserved.
22
■ Double click the Open File... Button to create the empty event handler (Fig. 23.11).
■ The ShowDialog method displays the Open dialog to allow the user to open a file, and returns a value of type DialogResult.
Creating a StreamWriter Object (Cont.)
Figure 23.11 | Displaying the Open dialog and retrieving the result.
Displaying Open dialog
If the user clicks Cancel, the
event handler exits without performing any actions
2009 Pearson Education, Inc. All rights reserved.
23
Creating a StreamWriter Object (Cont.)
■ Property FileName of OpenFileDialog (Fig. 23.12) specifies the full path of the file the user selected.
Figure 23.12 | Retrieving the name and path of selected file.
Setting variable to user-specified file name
2009 Pearson Education, Inc. All rights reserved.
24
■ Method CheckValidity determines whether the specified file is a text file (that is, the file name ends with ".txt").
■ The StreamWriter constructor takes two arguments.
– The first indicates the name of the file to which you write information.
– The second is a Boolean value that determines whether the StreamWriter appends information to the end of the file.
Creating a StreamWriter Object (Cont.)
2009 Pearson Education, Inc. All rights reserved.
25
Creating a StreamWriter Object (Cont.)
Figure 23.13 | Validating the filename and initializing a StreamWriter object.
Check for valid filename
Create StreamWriter object
2009 Pearson Education, Inc. All rights reserved.
26
Common Programming Error
When you open an existing file by invoking the StreamWriter constructor with a False second argument, data previously contained in the file is lost.
2009 Pearson Education, Inc. All rights reserved.
27
Writing Information to a Sequential-Access File
■ Method ClearUserInput (Fig. 23.14) clears the TextBoxes and resets the NumericUpDown control’s value.
Figure 23.14 | Clearing user input.
Clearing user input
2009 Pearson Education, Inc. All rights reserved.
28
■ Double click the Enter Button to create its event handler (Fig. 23.15).
■ Write the user input to the file by using the Write method. – Each field is separated by a Tab character.
■ The WriteLine method writes its argument to the file, followed by a newline character.
Writing Information to aSequential-Access File (Cont.)
Figure 23.15 | StreamWriter writing to a file.
Writing information to a file
2009 Pearson Education, Inc. All rights reserved.
29
■ Double click the Close File Button to create its event handler (Fig. 23.16).
■ The StreamWriter’s Close method closes the stream.
– You should always close the file after you’ve finished processing it to ensure that you don’t lose any data.
Closing the StreamWriter
Figure 23.16 | Closing the StreamWriter.
Closing StreamWriter object
2009 Pearson Education, Inc. All rights reserved.
30
Writing Event Information to a File
■ Run your application (Fig. 23.17).
Figure 23.17 | Write Event application running.
2009 Pearson Education, Inc. All rights reserved.
31
■ Click the Open File... Button and open the existing calendar.txt file from:
– C:\Examples\Tutorial23\TemplateApplication\TicketInformation\TicketInformation\bin\Debug (Fig. 23.18).
Writing Event Information to a File (Cont.)
Figure 23.18 | Open dialog displaying contents of the templateTicket Information application’s Debug folder.
2009 Pearson Education, Inc. All rights reserved.
32
■ Enter event information, then click Enter to add an event to the calendar.txt file.
■ When you have entered all the events you wish, click the Close File Button.
■ Use the IDE to open calendar.txt (Fig. 23.19).
Figure 23.19 | Sequential-access file generated by Write Event application.
Writing Event Information to a File (Cont.)
Day and time of event,
ticket price, eventname and description
2009 Pearson Education, Inc. All rights reserved.
33
1 Imports System.IO
2
3 Public Class WriteEventForm
4
5 Private output As StreamWriter
6
7 ' determine validity of file type
8 Private Function CheckValidity(ByVal name As String) As Boolean
9 ' show error if user specified invalid file
10 If name.EndsWith(".txt") = False Then
11 MessageBox.Show("File name must end with .txt", _
12 "Invalid File Type", _
13 MessageBoxButtons.OK, MessageBoxIcon.Error)
14 Return False ' to indicate invalid file type
15 ' change status of Buttons if file name is valid
16 Else
17 openFileButton.Enabled = False
18 enterButton.Enabled = True
19 closeFileButton.Enabled = True
20 Return True ' to indicate text file specified
21 End If
22 End Function ' CheckValidity
■ Figure 23.20 presents the source codefor the Write Event application.
Outline
System.IO
(1 of 4 )
Importing namespace System.IO
StreamWriter used towrite text to a file
2009 Pearson Education, Inc. All rights reserved.
34
23
24 ' handles Open File... Button's Click event
25 Private Sub openFileButton_Click(ByVal sender As System.Object, _
26 ByVal e As System.EventArgs) Handles openFileButton.Click
27
28 ' display Open dialog
29 Dim result As DialogResult = openFileDialog.ShowDialog()
30
31 ' open specified file if user did not click Cancel Button
32 If result <> Windows.Forms.DialogResult.Cancel Then
33 ' get specified filename
34 Dim fileName As String = openFileDialog.FileName
35
36 ' validate file name
37 If CheckValidity(fileName) = True Then
38 ' enable user to append data to file via StreamWriter
39 output = New StreamWriter(fileName, True)
40 End If
41 End If
42 End Sub ' openFileButton_Click
Outline
System.IO
(2 of 4 )
Retrieve user input from Open dialog
Storing filename entered by user
Create StreamWriter object to associate a stream with theuser-specified text file
2009 Pearson Education, Inc. All rights reserved.
35
43
44 ' clear TextBoxes and reset NumericUpDown control
45 Private Sub ClearUserInput()
46 dayUpDown.Value = 1
47 priceTextBox.Clear()
48 eventTextBox.Clear()
49 descriptionTextBox.Clear()
50 End Sub ' ClearUserInput
51
52 ' handles Enter Button’s Click event
53 Private Sub enterButton_Click(ByVal sender As System.Object, _
54 ByVal e As System.EventArgs) Handles enterButton.Click
55
56 ' using StreamWriter to write data to file
57 output.Write(dayUpDown.Value & ControlChars.Tab)
58 output.Write(timeDateTimePicker.Text & ControlChars.Tab)
59 output.Write(priceTextBox.Text & ControlChars.Tab)
60 output.Write(eventTextBox.Text & ControlChars.Tab)
61 output.WriteLine(descriptionTextBox.Text)
62 ClearUserInput() ' prepare GUI for more user input
63 End Sub ' enterButton_Click
Outline
System.IO
(3 of 4 )
Append data to end of file
Append data to end of file
2009 Pearson Education, Inc. All rights reserved.
36
64
65 ' handles Close File Button’s Click event
66 Private Sub closeFileButton_Click(ByVal sender As System.Object, _
67 ByVal e As System.EventArgs) Handles closeFileButton.Click
68
69 output.Close() ' close StreamWriter
70
71 ' allow user to open another file
72 openFileButton.Enabled = True
73 enterButton.Enabled = False
74 closeFileButton.Enabled = False
75 End Sub ' closeFileButton_Click
76 End Class ' WriteEventForm
Outline
System.IO
(4 of 4 )
Closing the file’s associated stream
2009 Pearson Education, Inc. All rights reserved.
37
When the Form loads:
Display the current day’s events
When the user selects a date on the calendar:
Display the selected day’s events
When the user selects an event from the Pick an event: ComboBox:
Retrieve index of selected item in the Pick an event: ComboBox
Display event information in the Description: TextBox
When procedure CreateEventList is called:
Extract data for the selected day from calendar.txt
Clear the Pick an event: ComboBox
23.5 Building the Ticket Information Application
2009 Pearson Education, Inc. All rights reserved.
38
If events are scheduled for that day
Add each event to the Pick an event: ComboBox
Display "- Events -" in the Pick an event: ComboBox
Display "Pick an event." in the Description: TextBox
Else
Display "- No Events -" in the Pick an event: ComboBox
Display "No events today." in the Description: TextBox
When procedure ExtractData is called:Clear the community events collection
Open calendar.txt file for reading
Until there are no events left in the file
Read the next line of the file
If the current event is for the day selected by the user
Store the event information
23.5 Building the Ticket InformationApplication (Cont.)
2009 Pearson Education, Inc. All rights reserved.
39
Action Control Event/Method
Label the application’s controls dateLabel, eventLabel, descriptionLabel
Application is run
TicketInfor-mationForm
Load
Display the current day’s events eventComboBox
dateMonthCalendar DateChanged
Display the selected day’s events eventComboBox, descriptionTextBox
■ Use an ACE table to convert the pseudocode into Visual Basic (Figure 23.21).
Figure 23.21 | ACE table for the Ticket Information application. (Part 1 of 3.)
Action/Control/Event (ACE) Table forthe Ticket Information Application
2009 Pearson Education, Inc. All rights reserved.
40
Action Control Event/Method
eventComboBox Selected-IndexChanged
Retrieve index of selected item in the
Pick an event: ComboBox
eventComboBox
Display event information in the
Description: TextBox
descriptionTextBox
CreateEventList
Extract data for the selected day from
calendar.txt
dateMonthCalendar
Clear the Pick an event: ComboBox eventComboBox
I f events are scheduled for that day
Add each event to the Pick an event:
ComboBox
eventComboBox, communityEvents
Display "- Events - " in the Pick an
event: ComboBox
eventComboBox
Figure 23.21 | ACE table for the Ticket Information application. (Part 2 of 3.)
Action/Control/Event (ACE) Table forthe Ticket Information Application (Cont.)
2009 Pearson Education, Inc. All rights reserved.
41
Action Control Event/Method
Display "Pick an event." in the
Description: TextBox
descriptionTextBox CreateEventList
Else
Display "- No Events - " in the Pick an
event: ComboBox
eventComboBox
Display "No events today." in the
Description: TextBox
descriptionTextBox
ExtractData
Clear the community events collection communityEvents
Open calendar.txt file for reading input
Until there are no events left in the file input
Read the next line of the file input
I f the current event is for the day
selected by the user
Store the event information
communityEvents
Figure 23.21 | ACE table for the Ticket Information application. (Part 3 of 3.)
Action/Control/Event (ACE) Table forthe Ticket Information Application (Cont.)
2009 Pearson Education, Inc. All rights reserved.
42
■ Open the TicketInformation template application and add the MonthCalendar control (Fig. 23.22).
■ Change its Name to dateMonthCalendar.
Adding a MonthCalendar Control
Figure 23.22 | Ticket Information template application’s Form.
2009 Pearson Education, Inc. All rights reserved.
43
Good Programming Practice
Append the MonthCalendar suffix to MonthCalendar control names.
2009 Pearson Education, Inc. All rights reserved.
44
■ Import namespace System.IO, which allows the application to use class StreamReader (Fig. 23.23).
Figure 23.23 | Importing the System.IO namespace.
Beginning to Build the TicketInformation Application
2009 Pearson Education, Inc. All rights reserved.
45
■ Store the event information read from the file in a List(Of CommunityEvent) named communityEvents (Fig. 23.24).
■ In the Solution Explorer, right click the TicketInformation project.
– Select Add > Existing Item...
– Select the CommunityEvent.vb file and click Add.
Beginning to Build the TicketInformation Application (Cont.)
Figure 23.24 | List declared to hold event information.
Creating a List of CommunityEvents
2009 Pearson Education, Inc. All rights reserved.
46
■ Double click the Form to generate its event handler (Fig. 23.25).
Figure 23.25 | Load event handler calling method CreateEventList.
Handling the Form’s Load Event
You add code to the CreateEventList
procedure later
2009 Pearson Education, Inc. All rights reserved.
47
■ Double click the MonthCalendar to generate the empty DateChanged event handler (Fig. 23.26).
Figure 23.26 | dateMonthCalendar’s DateChanged event handler.
Handling the MonthCalendar’sDateChanged Event
Calling method CreateEventList
2009 Pearson Education, Inc. All rights reserved.
48
■ The CreateEventList method (Fig. 23.27) declares currentEvent to iterate through the events.
– The currently selected date is specified by the MonthCalendar control’s SelectionStart property, which is the first date in any range selected.
Defining the CreateEventList Method
Figure 23.27 | CreateEventList calls method ExtractData andclears the ComboBox.
You add code to the ExtractData procedure
in the next box
2009 Pearson Education, Inc. All rights reserved.
49
■ The CreateEventList method (Fig. 23.28) has a For Each...Next statement.
– The statement iterates through List communityEvents and adds the name of each event to the ComboBox.
Defining the CreateEventList Method (Cont.)
Figure 23.28 | Displaying the events scheduled for the specified day.
Extracting event name from currentEvent and displaying
it in the ComboBox
Indicating that events are scheduled for the day
Indicating that no events are scheduled for the day
2009 Pearson Education, Inc. All rights reserved.
50
■ The Date selected in the MonthCalendar control is passed to the ExtractData method (Fig. 23.29).
■ Variable chosenDay is the selected day returned by the Day property of the currentDate parameter.
■ The eventInfo variable is an array of Strings used to store the event information retrieved from the file.
Reading a Sequential-Access File
Figure 23.29 | ExtractData method’s variable declarations.
2009 Pearson Education, Inc. All rights reserved.
51
■ ExtractData creates a new StreamReader object (Fig. 23.30), passing the name of the file to be read.
Figure 23.30 | Initializing the StreamReader used to read data froma sequential-access file.
Creating a StreamReader object to read the calendar.txt file
Reading a Sequential-Access File (Cont.)
2009 Pearson Education, Inc. All rights reserved.
52
■ The Do Until...Loop statement (Fig. 23.31) determines whether the end of the file has been reached.
■ The ReadLine method reads one line of text from the specified stream.
■ String method Split, splits the String at each Tab character, and assigns the resulting array of Strings to array eventInfo.
– This character is called a delimiter and is used to mark the boundaries between fields.
Reading a Sequential-Access File (Cont.)
2009 Pearson Education, Inc. All rights reserved.
53
Figure 23.31 | Extracting the day from an event entry in the file.
Verify that the end of thefile has not been reached
Reading a Sequential-Access File (Cont.)
Read a line of text from the file
Split the line of text into an array of Strings containing
each field in the record
2009 Pearson Education, Inc. All rights reserved.
54
■ If the day of the event read from the file and the specified day are the same, then the event information is stored in a CommunityEvent object (Fig. 23.32).
Reading a Sequential-Access File (Cont.)
Figure 23.32 | Storing event information in the List of CommunityEvents.
Store event information in a CommunityEvent object
Add the event to the List
2009 Pearson Education, Inc. All rights reserved.
55
■ Double click the Pick an event: ComboBox to generate its event handler (Fig. 23.33).
– The SelectedIndex property of the ComboBox returns the index number of the selected event.
Handling the SelectedIndexChanged Event
Displaying event information in the Description: TextBox
Figure 23.33 | Display information for selected event.
2009 Pearson Education, Inc. All rights reserved.
56
■ Rewrite the ExtractData method (Fig. 23.34).
Figure 23.34 | Removed Do Until...Loop and local variables.
Using LINQ to Select Events From a Text File
2009 Pearson Education, Inc. All rights reserved.
57
■ Variable eventQuery stores the LINQ query (Fig. 23.35) used to search the data from calendar.txt.
■ The From clause specifies the range variable and the data source.
■ File method ReadAllLines returns an array of Strings in which each element is a line from the text file passed as an argument.
Using LINQ to Select Events From a Text File (Cont.)
2009 Pearson Education, Inc. All rights reserved.
58
Figure 23.35 | Specifying the data source.
Using LINQ to Select Events From a Text File (Cont.)
Specifying the query’sdata source
2009 Pearson Education, Inc. All rights reserved.
59
■ A Let clause (Fig. 23.36) allows you to create and initialize a variable in a LINQ query.
– Line 47 declares an array of Strings named eventInfo.
■ The Where clause uses the array to determine whether the day of the event matches the selected day.
Declaring variable eventInfo inside the LINQ query
Figure 23.36 | Declaring a variable in a LINQ query.
Using LINQ to Select Events From a Text File (Cont.)
2009 Pearson Education, Inc. All rights reserved.
60
■ As a LINQ query executes, it can create new objects which are returned as the query’s result (Fig. 23.37).
– The With keyword specifies that the property names used are from the new CommunityEvent object.
Using LINQ to Select Events From a Text File (Cont.)
Figure 23.37 | Creating CommunityEvent objects in the Select clause.
Creates a new CommunityEvent object
2009 Pearson Education, Inc. All rights reserved.
61
■ Interface IEnumerable’s ToList method (Fig. 23.38) assigns the selected events to the List object communityEvents.
■ Method ToList returns a List of the items selected by the LINQ query.
Figure 23.38 | Assigning the query result to the List.
Using LINQ to Select Events From a Text File (Cont.)
2009 Pearson Education, Inc. All rights reserved.
62
1 Imports System.IO
2
3 Public Class TicketInformationForm
4
5 ' stores events
6 Private communityEvents As _
7 New List(Of CommunityEvent)()
8
9 ' populates ComboBox with current day’s events (if any)
10 Private Sub CreateEventList()
11
12 Dim currentEvent As CommunityEvent ' control variable
13
14 ' stores event information in List for selected day
15 ExtractData(dateMonthCalendar.SelectionStart)
16
17 ' remove any items in ComboBox
18 eventComboBox.Items.Clear()
19
■ Figure 23.39 presents the sourcecode for the application.
Outline
System.IO
(1 of 5 )Importing namespace System.IO
2009 Pearson Education, Inc. All rights reserved.
63
20 ' add each new event name to ComboBox
21 If communityEvents.Count > 0 Then
22 For Each currentEvent In communityEvents
23 ' extract and display event name
24 eventComboBox.Items.Add(currentEvent.Name)
25 Next
26
27 ' inform user that events are scheduled
28 eventComboBox.Text = " - Events - "
29 descriptionTextBox.Text = "Pick an event."
30
31 Else ' inform user that no events are scheduled
32 eventComboBox.Text = " - No Events - "
33 descriptionTextBox.Text = "No events today."
34 End If
35 End Sub ' CreateEventList
36
Outline
System.IO
(2 of 5 )
2009 Pearson Education, Inc. All rights reserved.
64
37 ' extracts event data for a specified day from calendar.txt
38 Private Sub ExtractData(ByVal currentDate As Date)
39 ' set to selected date in MonthCalendar control
40 Dim chosenDay As Integer = currentDate.Day
41
42 communityEvents.Clear() ' clear the List of events
43
44 ' select the events from the file scheduled for selected day
45 Dim eventQuery = _
46 From line In File.ReadAllLines("calendar.txt") _
47 Let eventInfo As String() = line.Split(ControlChars.Tab) _
48 Where Convert.ToInt32(eventInfo(0)) = chosenDay _
49 Select New CommunityEvent With _
50 { _
51 .Day = chosenDay, _
52 .Time = eventInfo(1), _
53 .Price = Convert.ToDecimal(eventInfo(2)), _
54 .Name = eventInfo(3), _
55 .Description = eventInfo(4) _
56 } ' end LINQ query that creates CommunityEvent objects
Outline
System.IO
(3 of 5 )
Retrieve an array containing each line of calendar.txt
Split line into arrayof Strings
Check whether chosenDay is the day from the line being processed
Creating a CommunityEvent object with an object initializer
2009 Pearson Education, Inc. All rights reserved.
65
57
58 ' assign the selected events to the List
59 communityEvents = eventQuery.ToList()
60 End Sub ' ExtractData
61
62 ' handles Form’s Load event
63 Private Sub TicketInformationForm_Load( _
64 ByVal sender As System.Object,ByVal e As System.EventArgs) _
65 Handles MyBase.Load
66
67 ' display any events scheduled for today in ComboBox
68 CreateEventList()
69 End Sub ' TicketInformationForm_Load
70
71 ' handles MonthCalendar’s DateChanged event
72 Private Sub dateMonthCalendar_DateChanged( _
73 ByVal sender As System.Object, _
74 ByVal e As System.Windows.Forms.DateRangeEventArgs) _
75 Handles dateMonthCalendar.DateChanged
76
Outline
System.IO
(4 of 5 )
Retrieve a List containing each CommunityEvent object in the query result
2009 Pearson Education, Inc. All rights reserved.
66
77 ' display any events for the specified date in ComboBox
78 CreateEventList()
79 End Sub ' dateMonthCalendar_DateChanged
80
81 ' handles ComboBox’s SelectedIndexChanged event
82 Private Sub eventComboBox_SelectedIndexChanged(ByVal sender As _
83 System.Object, ByVal e As System.EventArgs) _
84 Handles eventComboBox.SelectedIndexChanged
85
86 ' get the event selected in the ComboBox
87 Dim selectedEvent As CommunityEvent = _
88 communityEvents(eventComboBox.SelectedIndex)
89
90 ' place time, price and description of event in TextBox
91 descriptionTextBox.Text =
92 selectedEvent.Time & ControlChars.CrLf & _
93 "Price: $" & selectedEvent.Price & ControlChars.CrLf & _
94 selectedEvent.Description
95 End Sub ' eventComboBox_SelectedIndexChanged
96 End Class ' TicketInformationForm
Outline
System.IO
(5 of 5 )