T U T O R I A L Completing the Inventory Application Introducing Programming  2009 Pearson Education, Inc.

Download Report

Transcript T U T O R I A L Completing the Inventory Application Introducing Programming  2009 Pearson Education, Inc.

1
T U T O R I A L
5
Completing the
Inventory
Application
Introducing Programming
 2009 Pearson Education, Inc. All rights reserved.
2
Outline
Test-Driving the Inventory Application
Introduction to Visual Basic Code
Inserting an Event Handler
Performing a Calculation and Displaying the
Result
5.5 Using the IDE to Eliminate Compilation Errors
5.1
5.2
5.3
5.4
 2009 Pearson Education, Inc. All rights reserved.
3
Objectives
In this tutorial you will learn:
■ Add an event handler for a Button control.
■ Insert code into an event handler.
■ Access a property’s value by using Visual Basic
code.
■ Use the assignment and multiplication operators.
■ Use the Visual Basic IDE to fix compilation errors.
 2009 Pearson Education, Inc. All rights reserved.
4
Introduction
■ You will add functionality to the Inventory
application that you designed in Tutorial 4.
■ The term functionality describes the actions an
application can execute.
■ GUI events, represent user actions, such as clicking
a Button or altering a value in a TextBox.
■ Event handlers are pieces of code that execute when
such events occur.
■ Events and event handlers are crucial to programming
Windows applications.
 2009 Pearson Education, Inc. All rights reserved.
5
5.1 Test-Driving the Inventory Application
Application Requirements
A college bookstore receives cartons of textbooks.
In each shipment, all cartons contain the same number
of textbooks. The inventory manager wants to use a
computer to calculate the total number of textbooks
arriving at the bookstore for each shipment. The
inventory manager will enter the number of cartons
received and the fixed number of textbooks in each
carton for each shipment; then the application will
calculate the total number of textbooks in the shipment.
 2009 Pearson Education, Inc. All rights reserved.
6
Test-Driving the Inventory Application
■ Open the directory C:\Examples\Tutorial05\
CompletedApplication\Inventory2. Double
click Inventory2.sln to open the application.
■ Select Debug > Start Debugging to run the
application (Fig. 5.1).
Figure 5.1 | Inventory application with quantities entered.
 2009 Pearson Education, Inc. All rights reserved.
7
Test-Driving the Inventory Application (Cont.)
■ Click the Calculate Total button.
■ The application multiplies the two numbers you
entered and displays the result in the Label to the
right of Total: (Fig. 5.2).
Result of calculation
Figure 5.2 | Result of clicking the Calculate Total Button
in the Inventory application.
 2009 Pearson Education, Inc. All rights reserved.
8
Customizing the IDE
■ Enable the IDE’s capability to show line numbers in your code:
– Select Tools > Options... (Fig. 5.3).
– In the Text Editor Basic category, select the Editor
category and locate the Interaction group of CheckBoxes.
– Make sure the CheckBox next to Line numbers is checked.
Text Editor Basic category
Show all settings CheckBox
Figure 5.3 | Options dialog.
 2009 Pearson Education, Inc. All rights reserved.
9
Customizing the IDE (Cont.)
■ Use proper spacing when writing code.
■ Indenting code improves program readability.
■ In the Options dialog (Fig. 5.4), enter 3 for both the tab size
and indent size, or use the Smart indenting feature.
Text Editor Basic category
Editor Category
Smart indenting feature
Line numbers CheckBox
(checked)
Figure 5.4 | General settings page for Visual Basic text editor.
 2009 Pearson Education, Inc. All rights reserved.
10
Customizing the IDE (Cont.)
■ In the Environment category, select the Fonts
and Colors category.
■ Click the Use Defaults Button (Fig. 5.5).
■ Click the OK Button to apply any changes.
Use Defaults Button
Fonts and Colors category
Figure 5.5 | Examining the Fonts and Colors page.
 2009 Pearson Education, Inc. All rights reserved.
11
Common Programming Practice
You can change the font and color settings if you
prefer a different appearance for your code. To remain
consistent with this book, however, we recommend
that you not change the default font and color settings.
 2009 Pearson Education, Inc. All rights reserved.
12
Introducing Visual Basic Code
■ Double click the Inventory.vb file in the Solution
Explorer window.
■ Switch to Code view (Fig. 5.6) by selecting
View > Code or pressing F7.
Inventory.vb tabbed window
Class definition
Figure 5.6 | IDE showing code for the Inventory application.
 2009 Pearson Education, Inc. All rights reserved.
13
Introducing Visual Basic Code (Cont.)
■ Most Visual Basic programs consist of pieces called
classes, which simplify application organization.
■ Classes contain groups of code statements that
perform tasks and return information when the tasks
are completed.
– These lines collectively are called a class definition.
■ Most Visual Basic applications consist of a
combination of code written by programmers and
preexisting classes written and provided by Microsoft
in the .NET Framework Class Library.
 2009 Pearson Education, Inc. All rights reserved.
14
Introducing Visual Basic Code (Cont.)
■ Line 1 begins the class definition.
■ The Class keyword introduces a class definition
in Visual Basic and is followed by the class name.
■ The name of the class is an identifier
– An identifier is a series of characters consisting of letters,
digits and underscores.
– Identifiers cannot begin with a digit and cannot contain
spaces.
■ The class definition ends at line 3 with the keywords
End Class.
 2009 Pearson Education, Inc. All rights reserved.
15
Common Programming Practice
Capitalize the first letter of each class identifier, such
as the Form name.
 2009 Pearson Education, Inc. All rights reserved.
16
Introducing Visual Basic Code (Cont.)
■ Keywords (or reserved words) are reserved for use
by Visual Basic.
■ Keywords appear in blue by default in the IDE.
■ A complete list of Visual Basic keywords can be found
in Appendix E, Keyword Chart.
■ Visual Basic keywords and identifiers are not case
sensitive.
■ The IDE applies the correct case to each letter of a
keyword and identifier, so when you type clasS, it
changes to Class when you press the Enter key.
 2009 Pearson Education, Inc. All rights reserved.
17
Adding a Button’s Click Event Handler
■ Click the Inventory.vb [Design] tab to view the
Windows Form Designer. Then double click the
Calculate Total Button to enter Code view.
■ The code for the application, which now includes the
new event handler in lines 3–5 of Fig. 5.7, is displayed.
Asterisks indicate unsaved
changes to application
Empty event handler
Figure 5.7 | Event handler calculateButton_Click
before you add your program code.
 2009 Pearson Education, Inc. All rights reserved.
18
Adding a Button’s Click Event Handler (Cont.)
■ Double clicking the Calculate Total Button
caused the Visual Basic IDE to generate the
Button’s Click event handler.
– The event handler is the code that executes when the user
clicks the Calculate Total Button.
– When you double click a control, the IDE inserts an event
handler for that control.
 2009 Pearson Education, Inc. All rights reserved.
19
Adding a Button’s Click Event Handler (Cont.)
■ At the end of each event handler’s first line, Visual
Basic inserts a Handles clause. Scroll to the right
in Code view to see the Handles clause for the
Calculate Total Button’s Click event
handler (line 3).
Handles calculateButton.Click
■ This Handles clause indicates that the event
handler is called when the calculateButton’s
Click event occurs.
 2009 Pearson Education, Inc. All rights reserved.
20
Adding a Button’s Click Event Handler (Cont.)
■ In Visual Basic, event handlers follow the naming
scheme controlName_eventName.
■ This convention mimics the event handler’s
Handles clause.
■ The word controlName refers to the name of the
control provided in its Name property (in this case,
calculateButton).
■ The word eventName represents the name of the
event (in this case, Click) raised by the control.
– When event eventName occurs on the control
controlName, event handler controlName_eventName
executes.
 2009 Pearson Education, Inc. All rights reserved.
21
Adding a Button’s Click Event Handler (Cont.)
■ Run the application (Fig. 5.8).
Close box
Figure 5.8 | Running the application without functionality.
 2009 Pearson Education, Inc. All rights reserved.
22
Adding Code to an Empty Event Handler
■ Select View > Code to view the application’s
code (Fig. 5.9).
Event handler
Type this code
Figure 5.9 | Code added to the Calculate Total Button’s event handler.
 2009 Pearson Education, Inc. All rights reserved.
23
Adding Code to an Empty Event Handler (Cont.)
■ A single-quote character ('), indicates that the
remainder of the line is a comment.
– You insert comments in programs to improve the readability of
your code.
– Comments explain the code so that other programmers who
need to work with the application can understand it more easily.
By default, comments are displayed in green.
– Comments also help you read your own code.
■ Comments can be placed either on their own lines
(these are called “full-line comments”) or at the end of
a line of Visual Basic code.
■ Comments do not cause the computer to perform any
actions when your applications run.
 2009 Pearson Education, Inc. All rights reserved.
24
Common Programming Practice
Comments written at the end of a line should be
preceded by a space, to enhance program readability.
 2009 Pearson Education, Inc. All rights reserved.
25
Adding Code to an Empty Event Handler (Cont.)
■ A Visual Basic statement performs an action.
■ By default, statements end when the current line
ends.
■ In Visual Basic, properties are accessed in code
by placing a period between the control name.
– This period is called the member-access operator (.),
or the dot operator.
 2009 Pearson Education, Inc. All rights reserved.
26
Adding Code to an Empty Event Handler (Cont.)
■ When the control name and member-access operator
are typed, a window appears listing that object’s
members (Fig. 5.10).
Description of selected member
Selected member
IntelliSense
Figure 5.10 | IntelliSense activating while entering code.
 2009 Pearson Education, Inc. All rights reserved.
27
Adding Code to an Empty Event Handler (Cont.)
■ This feature, known as IntelliSense, displays items
that can be used in the current context.
– The IntelliSense window can also be opened by pressing
Ctrl + Space.
– Click the member name once to display a description of that
member; double click it to add the member’s name to your
application. You can also press Enter or Tab to insert the
member
– The Common tab shows the most commonly used members.
The All tab shows every member that can appear to the right of
the dot operator.
 2009 Pearson Education, Inc. All rights reserved.
28
Adding Code to an Empty Event Handler (Cont.)
■ The “=” symbol is known as the assignment
operator.
■ The expressions on either side of the assignment
operator are referred to as its operands.
– This assignment operator assigns the value on the right of
the operator (the right operand) to the variable on the left
of the operator (the left operand).
■ The assignment operator is known as a binary
operator.
 2009 Pearson Education, Inc. All rights reserved.
29
Adding Code to an Empty Event Handler (Cont.)
■ The entire statement is called an assignment
statement because it assigns a value to the left
operand.
■ Note that the right operand is unchanged by the
assignment statement.
■ Run the application and test its output (Fig. 5.11).
Result of clicking Calculate Total Button
Figure 5.11 | Running the application with the event handler.
 2009 Pearson Education, Inc. All rights reserved.
30
Completing the Inventory Application
■ The underscore character used in Figure 5.12 is
known as the line-continuation character.
– At least one space character must precede each linecontinuation character.
■ A whitespace character is a space, tab or newline.
Modified Inventory
application code
Figure 5.12 | Using multiplication in the Inventory application.
 2009 Pearson Education, Inc. All rights reserved.
31
Common Programming Practice
A lengthy statement may be spread over several lines.
If a single statement must be split across lines, choose
breaking points that make sense, such as after an
operator. If a statement is split across two or more
lines, indent all subsequent lines with one “level” of
indentation.
 2009 Pearson Education, Inc. All rights reserved.
32
Common Programming Error
Splitting a statement over several lines without
including the line-continuation character is a
compilation error.
 2009 Pearson Education, Inc. All rights reserved.
33
Common Programming Error
Placing non-whitespace characters, including
comments, to the right of a line-continuation character
is a compilation error.
 2009 Pearson Education, Inc. All rights reserved.
34
Completing the Inventory Application (Cont.)
■ The asterisk (*) is known as the multiplication
operator.
– Its left and right operands are multiplied together.
■ The Val function prevents nonnumeric inputs from
terminating the application. A function is a piece of
code that performs a task when called and returns a
value.
– The values returned by Val become the values used in
the multiplication expression.
 2009 Pearson Education, Inc. All rights reserved.
35
Completing the Inventory Application (Cont.)
■ Call functions by typing their name followed by
parentheses.
■ Any values inside the parentheses are known as
function arguments.
– Arguments are inputs to the function.
– In this case, the argument specifies which value you want
to send to function Val.
 2009 Pearson Education, Inc. All rights reserved.
36
Completing the Inventory Application (Cont.)
■ Function Val obtains a value from a string of
characters.
■ Val reads its argument one character at a time
until it encounters a character that is not a number.
■ Val recognizes the decimal point as a numeric
character, as well as the plus and minus signs
when they appear at the beginning of the string.
 2009 Pearson Education, Inc. All rights reserved.
37
Completing the Inventory Application (Cont.)
■ Once a nonnumeric character is read, Val returns
the number it has read up to that point.
– Val ignores whitespace characters.
– Val does not recognize symbols such as commas and
dollar signs.
– If function Val receives an argument that cannot be
converted to a number, it returns 0.
 2009 Pearson Education, Inc. All rights reserved.
38
Completing the Inventory Application (Cont.)
■ Be careful when using Val—although the value returned is
a number, it is not always the value the user intended (see
Fig. 5.13).
■ If incorrect data is entered by the user, Val makes no
indication of the error.
Val Function call examples
Results
Val(
Val(
Val(
Val(
Val(
Val(
Val(
Val(
16
–3
1.5
67
8
14
12345
0
"16" )
"–3" )
"1.5" )
"67a4" )
"8+5" )
"14 Main St." )
"+1 2 3 4 5" )
"hello" )
Figure 5.13 | Val function call examples.
 2009 Pearson Education, Inc. All rights reserved.
39
Outline
■ Figure 5.14 presents the Inventory application’s code.
1
Public Class InventoryForm
2
3
Private Sub calculateButton_Click( _
4
ByVal sender As System.Object, ByVal e As System.EventArgs) _
5
6
Handles calculateButton.Click
7
8
' multiply values input and display result in Label
totalResultLabel.Text = _
9
Val(cartonsTextBox.Text) * Val(itemsTextBox.Text)
10
End Sub ' calculateButton_Click
11 End Class ' InventoryForm
 2009 Pearson Education, Inc. All rights reserved.
40
5.5 Using the IDE to Eliminate Compilation Errors
■ Debugging is the process of fixing errors in an
application.
■ There are two types of errors—compilation errors and
logic errors.
– Compilation errors occur when code statements violate
the grammatical rules of the programming language or
when code statements are simply incorrect in the current
context.
– Compilation errors include misspellings, failure to use the
line-continuation character when splitting a statement
across multiple lines or using an identifier in the wrong
context.
 2009 Pearson Education, Inc. All rights reserved.
5.5 Using the IDE to Eliminate
Compilation Errors (Cont.)
41
– Syntax errors are compilation errors that are violations of
the grammatical rules of the programming language.
– Logic errors do not prevent the application from compiling
successfully, but do cause the application to produce
erroneous results.
■ The Visual Basic IDE contains a debugger that allows
you to analyze the behavior of your application.
 2009 Pearson Education, Inc. All rights reserved.
5.5 Using the IDE to Eliminate
Compilation Errors (Cont.)
42
■ You can compile an application without executing it by
selecting Build > Build [Project Name].
■ The Output window (Fig. 5.15) displays the result of
the compilation.
– Select Debug > Windows > Output to view it while
debugging.
Figure 5.15 | Results of successful build in the Output window.
 2009 Pearson Education, Inc. All rights reserved.
5.5 Using the IDE to Eliminate
Compilation Errors (Cont.)
43
■ Compilation errors appear in the Error List window along with
a description of each error.
■ Figure 5.16 displays the error that appears when the linecontinuation character is left out of a multiple-line statement.
■ Double click the error in the Error List window to go the
location of the error in the code.
■ For additional information on a compilation error, right click the
error statement in the Error List window and select Show
Error Help.
Figure 5.16 | Error List lists compilation errors.
 2009 Pearson Education, Inc. All rights reserved.
44
Using the IDE to Eliminate Compilation Errors
■ The Visual Basic IDE provides real-time error
checking (Fig. 5.17).
Indicates compilation error
Figure 5.17 | IDE with compilation errors.
 2009 Pearson Education, Inc. All rights reserved.
45
Using the IDE to Eliminate Compilation Errors (Cont.)
■ Open the Error List window (Fig. 5.18) by selecting
View > Error List.
Figure 5.18 | Error List displaying the compilation errors.
■ These features notify you of possible errors and give you a
chance to fix them before compiling the application.
■ The IDE refuses to run your modified application until all
compilation errors have been corrected.
 2009 Pearson Education, Inc. All rights reserved.
46
Using the IDE to Eliminate Compilation Errors (Cont.)
■ Double clicking an error in the Error List window
selects the code containing that error.
■ Placing the cursor over the compilation error
displays the error message (Fig. 5.19).
Highlighted compilation error
Figure 5.19 | Highlighting the code where a compilation error occurs.
 2009 Pearson Education, Inc. All rights reserved.
47
Using the IDE to Eliminate Compilation Errors (Cont.)
■ Additional help regarding the compilation error is
also available through the Error List item’s
context menu, which you can access by right
clicking an item (Fig. 5.20).
Context help
Figure 5.20 | Getting additional help.
 2009 Pearson Education, Inc. All rights reserved.
48
Using the IDE to Eliminate Compilation Errors (Cont.)
■ This displays a helpful reference page (Fig. 5.21).
Suggested solutions to
misspelled identifier
(note that the debugger
interprets the misspelling
as a new, undeclared
identifier)
Figure 5.21 | Error Help window.
 2009 Pearson Education, Inc. All rights reserved.
49
Using the IDE to Eliminate Compilation Errors (Cont.)
■ When you correct an error, note that the jagged
line does not disappear immediately.
■ When you move the cursor to another line, the
IDE rechecks the code for errors and removes the
jagged underline.
 2009 Pearson Education, Inc. All rights reserved.
50
Using the IDE to Eliminate Compilation Errors (Cont.)
■ Hover over the small red rectangle located at a
compilation error.
– The Error Correction Options icon ( ) appears.
– Click this icon to open the Error Correction
Options window (Fig. 5.22).
Figure 5.22 | Using the Error Correction window to fix a compilation error.
 2009 Pearson Education, Inc. All rights reserved.