VB Chapter 3

Download Report

Transcript VB Chapter 3

Microsoft Visual Basic:
Reloaded
Chapter Three
Memory Locations and Calculations
2
Overview
■
■
■
■
■
■
■
■
■
■
Class Definitions
Events and Event Handlers
Adding Code to an Event Handler
Val Function and TextChanged Event
Declaring Variables
TryParse and Convert Class Methods
Arithmetic (+,-,*,/,\,^,Mod)
Variable Scope and Lifetime
Option Explicit, Infer and Strict
Debugging Errors and Debugger Breakpoints
 2009 Pearson Education, Inc. All rights reserved.
3
Class Definitions
■ 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.
4
Class Definition and Code
Public Class Form1
Private Sub Button1_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs)
Handles Button1.Click
MessageBox.Show("Hello World!")
End Sub
End Class
 2009 Pearson Education, Inc. All rights reserved.
5
Class Definitions
■ 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 with the keywords End
Class.
 2009 Pearson Education, Inc. All rights reserved.
6
Events and Event Handlers
■ 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.
■ When you double click a control, the IDE inserts
the default event handler for that control.
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
End Sub
 2009 Pearson Education, Inc. All rights reserved.
7
Default Control Events
■
■
■
■
■
Button: Click
Text Box: TextChanged
Radio Button: CheckedChanged
Check Box: CheckedChanged
Combo Box: SelectedIndexChanged
■ Double click on the control in design view to
automatically open the code window with the
default event for that control.
 2009 Pearson Education, Inc. All rights reserved.
8
Other Command Button Events
■
■
■
■
■
■
Enter
TextChanged
KeyDown
MouseEnter
MouseLeave
MouseHover
■ And many more (68 in all) which can be explored
in the Object Browser, Properties Window or
Code Window
 2009 Pearson Education, Inc. All rights reserved.
9
Default Event Handler for Button
Private Sub Button1_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs)
Handles Button1.Click
End Sub
■ When event eventName occurs on the control
controlName, event handler
controlName_eventName executes.
■ When event Click occurs on the control Button1,
event handler Button1_Click executes.
■ The Handles clause indicates that the event
handler is called when the Button’s
Click event occurs.
 2009 Pearson Education, Inc. All rights reserved.
10
Common Programming Statements
■ Message statements give information to the user
■ Declaration statements set variable names and
variable types
■ Assignment statements assign a value to a variable
■ Comparison statements compare one value to
another. They ask a true/false question.
■ Decision statements execute different lines of code
based on a comparison
■ Looping statements execute blocks of code again
and again
 2009 Pearson Education, Inc. All rights reserved.
11
Adding Code to an Event Handler
Figure 5.11 | Running the application with the event handler.
 2009 Pearson Education, Inc. All rights reserved.
12
Adding Code to an Event Handler
Public Class InventoryForm
Private Sub calculateButton_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs)
Handles calculateButton.Click
totalResultLabel.Text = cartonsTextBox.Text _
* itemsTextBox.Text
End Sub
End Class
 2009 Pearson Education, Inc. All rights reserved.
13
Adding Code to an Event Handler
■ 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.
■ The underscore character is the line-continuation
character.
At least one space character must precede each linecontinuation character.
Only whitespace characters (space, tab or newline) can follow
the underscore
 2009 Pearson Education, Inc. All rights reserved.
14
Adding Code to an Event Handler
■ 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.
■ The asterisk (*) is known as the multiplication
operator.
Its left and right operands are multiplied together.
 2009 Pearson Education, Inc. All rights reserved.
15
Enhancing the Code with the Val Function
Public Class InventoryForm
Private Sub calculateButton_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
calculateButton.Click
totalResultLabel.Text = Val(cartonsTextBox.Text) * _
Val(itemsTextBox.Text)
End Sub
End Class
 2009 Pearson Education, Inc. All rights reserved.
16
Val Function
■ 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.
■ Call functions by typing their name followed by
parentheses.
Val (“2 3kdd.3”)
 2009 Pearson Education, Inc. All rights reserved.
17
Val Function
■ Once a nonnumeric character is read, Val returns
the number it has read up to that point.
Val ignores whitespace characters.
Val (“2 34”) returns 234
Val does not recognize symbols such as commas and dollar
signs.
Val (“1,005”) returns 1
If function Val receives an argument that cannot be
converted to a number, it returns 0.
Val (“abc123”) returns 0
■ 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.
18
Val Function
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.
19
Enhancing the Inventory Application
■ The result displayed in the Total: Label will be
removed (Fig. 6.3) when the user enters a new
quantity in either TextBox.
Cleared output Label
Figure 6.3 | Enhanced Inventory application clears output Label after new input.
 2009 Pearson Education, Inc. All rights reserved.
20
TextChanged Event
■ Double click the Cartons per shipment: TextBox to
generate an event handler for the TextChanged event
(Fig. 6.9).
■ The notation "" in line 28 is called an empty string, which
is a value that does not contain any characters.
TextChanged event handler
Figure 6.9 | TextChanged event handler for Cartons per shipment: TextBox.
 2009 Pearson Education, Inc. All rights reserved.
Internal Memory
■ Internal memory: a component inside a computer
comprised of memory locations
■ Each memory location has a unique numeric
address and can hold only one item at a time
■ A programmer can reserve memory locations for a
program by assigning each location a name, a data
type, and an initial value
■ Data type: indicates the type of data the memory
location will store
■ Two types of memory locations that a programmer
can declare: variables and constants
 2009 Pearson Education, Inc. All rights reserved.
Variables
■ Variables: computer memory locations used to
temporarily store data while an application is
running
Contents can change during run time
■ Use a meaningful variable name that reflects the
purpose of the variable
■ Use camel casing for variable identifiers
■ Variable names should conform to naming rules
■ All variables must be declared by using program
code.
Declarations that you’ll make within event handlers begin
with the keyword Dim.
 2009 Pearson Education, Inc. All rights reserved.
23
Variables
■ Variable names—such as cartons, items and
result—correspond to actual locations in the
computer’s memory.
■ Every variable has a name, type, size and value.
cartons = Val(cartonsTextBox.Text)
■ Whenever a value is placed in a memory location,
this value replaces the value previously stored in that
location. The previous value is overwritten (lost).
■ Whenever a value is read from a memory location, the
process is nondestructive.
 2009 Pearson Education, Inc. All rights reserved.
 2009 Pearson Education, Inc. All rights reserved.
Variable Data Types
■ Each variable must be assigned a data type, which
determines the memory location’s data type
■ Each data type is a class
Integer, Long, or Short data types can store integers (whole
numbers)
Decimal, Double, and Single data types: store real numbers
(numbers with a decimal place)
Char data type: stores one Unicode character
String data type: stores multiple Unicode characters
 2009 Pearson Education, Inc. All rights reserved.
Figure 3-3: Basic data types in Visual Basic
 2009 Pearson Education, Inc. All rights reserved.
Declaring a Variable in Code
■ Declaration statement: used to declare, or
create, a variable
Declaration statement includes:
Scope keyword: Dim, Private, or Static
Name of the variable and data type
Initial value (optional)
■ Initialization
Numeric data types: automatically initialized to 0
String data type: automatically initialized to Nothing
Boolean data type: initialized to False
 2009 Pearson Education, Inc. All rights reserved.
Declaring a Variable in Code (cont’d.)
 2009 Pearson Education, Inc. All rights reserved.
Declaring a Variable in Code (cont’d.)
 2009 Pearson Education, Inc. All rights reserved.
1 Public Class InventoryForm
2
' handles Click event
3
4
5
Private Sub calculateButton_Click(ByVal sender As _
System.Object, ByVal e As System.EventArgs) _
Handles calculateButtton.Click
6
7
8
' declare variables
Dim cartons As Integer
9
10
11
Dim items As Integer
Dim result As Integer
12
13
' retrieve numbers from TextBoxes
cartons = Val(cartonsTextBox.Text)
14
15
16
items = Val(itemsTextBox.Text)
17
18
result = cartons * items
Use keyword Dim to declare
variables inside
an event handler
Assigning a property’s value to
a variable
' multiply two numbers
 2009 Pearson Education, Inc. All rights reserved.
31
19
20
21
' display result in Label
Assigning a
variable’s value
to a property
totalResultLabel.Text = result
End Sub ' calculateButton_Click
22
23
24
25
26
27
28
' handles TextChanged event for cartonsTextBox
Private Sub cartonsTextBox_TextChanged(ByVal sender As _
System.Object, ByVal e As System.EventArgs) _
Handles cartonsTextBox.TextChanged
totalResultLabel.Text = "" ' clear output Label
29
30
End Sub ' cartonsTextBox_TextChanged
31
' handles TextChanged event for itemsTextBox
32
33
Private Sub itemsTextBox_TextChanged(ByVal sender As _
System.Object, ByVal e As System.EventArgs) _
34
Handles itemsTextBox.TextChanged
35
36
totalResultLabel.Text = "" ' clear output Label
Setting a Label’s Text
property to an empty string
37
End Sub ' itemsTextBox_TextChanged
38 End Class ' InventoryForm
 2009 Pearson Education, Inc. All rights reserved.
32
Implicit Conversion
■ The Val function returns a numerical value as
data type Double when converting a value
retrieved from a TextBox’s Text property.
■ Lines 13–14 implicitly convert the Doubles to
Integer values. This process is called implicit
conversion because the conversion is performed
by Visual Basic without any additional code.
Implicit conversions from Double to Integer are generally
considered poor programming practice due to the potential
loss of information.
 2009 Pearson Education, Inc. All rights reserved.
Using the TryParse Method
■ TryParse method:
Part of every numeric data type’s class
Used to convert a string to that numeric data type
■ Argument: a value that is provided to a method
■ Basic syntax of TryParse method has two
arguments:
String: string value to be converted
Variable: location to store the result
■ If TryParse conversion is successful, the
method stores the value in the variable
■ If unsuccessful, a 0 is stored in the numeric
variable
 2009 Pearson Education, Inc. All rights reserved.
Figure 3-6: How to use the basic syntax of the TryParse method
 2009 Pearson Education, Inc. All rights reserved.
Using the TryParse Method (cont'd.)
 2009 Pearson Education, Inc. All rights reserved.
Using the Convert Class Methods
■ Convert class:
Contains methods for converting numeric values to specific
data types
■ Commonly used methods of the Convert class
include:
ToDouble
ToDecimal
ToInt32
ToString
 2009 Pearson Education, Inc. All rights reserved.
Using the Convert Class Methods (cont’d.)
 2009 Pearson Education, Inc. All rights reserved.
38
Arithmetic
VB .NET
operation
Arithmetic Algebra
operator
Visual Basic
code
Addition
+
f+7
f + 7
Subtraction
–
p–c
p - c
Multiplication
*
bm
b * m
Division (float)
/
x y or
x
or x ÷ y
x / y
y
Division (integer)
\
none
v \ u
Modulus
Mod
r mod s
r Mod s
Exponentiation
^
qp
q ^ p
Unary Negative
-
–e
–e
Unary Positive
+
+g
+g
Figure 6.15 | Arithmetic operators.
 2009 Pearson Education, Inc. All rights reserved.
39
Arithmetic
■ Arithmetic expressions in Visual Basic must be written
in straight-line form so that you can type them into a
computer.
For example, the division of 7.1 by 4.3 must be
written as 7.1 / 4.3.
Also, raising 3 to the second power cannot be written
as 32 but is written in straight-line form as 3 ^ 2.
■ Parentheses are used in Visual Basic expressions to
group operations in the same manner as in algebraic
expressions. To multiply a times the quantity b + c,
you write
a * ( b + c )
 2009 Pearson Education, Inc. All rights reserved.
40
Rules of Operator Precedence
■ Expressions in parentheses are evaluated first.
With nested parentheses, the operators contained in the
innermost pair of parentheses are applied first.
■
■
■
■
■
■
Exponentiation
Unary positive and negative, + and Multiplication and floating-point division
Integer division
Modulus operations
Addition and subtraction
Operators of the same type are applied from left to right.
 2009 Pearson Education, Inc. All rights reserved.
41
Rules of Operator Precedence
■ Let’s consider several expressions in light of the
rules of operator precedence.
The following calculates the average of three numbers:
Algebra:
m=(a+b+c)
3
Visual Basic:
m = ( a + b + c ) / 3
The parentheses are required because floating-point division has
higher precedence than addition.
The following is the equation of a straight line:
Algebra:
y = mx + b
Visual Basic:
y = m * x + b
No parentheses are required due to operator precedence.
 2009 Pearson Education, Inc. All rights reserved.
42
Rules of Operator Precedence
■ Consider how the expression y = ax2 + bx + c is
evaluated:
■ It is acceptable to place redundant parentheses in
an expression to make the expression easier to read.
y = ( a * ( x ^ 2 ) ) + ( b * x ) + c
 2009 Pearson Education, Inc. All rights reserved.
43
Integer and Floating-Point Division
■ Visual Basic has separate operators for integer
division (the backslash, \) and floating-point
division (the forward slash, /).
Floating-point division divides two numbers and returns a
floating-point number.
The operator for integer division treats its operands as
integers and returns an integer result.
■ Attempting to divide by zero is a runtime error
(that is, an error that has its effect while the
application executes). Dividing by zero terminates
an application.
 2009 Pearson Education, Inc. All rights reserved.
44
Integer Division Rounding
■ When floating-point numbers (numbers with
decimal points) are used with the integer-division
operator, the numerators and denominators are
first rounded as follows:
numbers ending in .5 are rounded to the nearest even integer—for
example, 6.5 rounds down to 6 and 7.5 rounds up to 8
all other floating-point numbers are rounded to the nearest integer—
for example, 7.1 rounds down to 7 and 7.7 rounds
up to 8.
■ Any fractional part of the integer division result is
truncated.
 2009 Pearson Education, Inc. All rights reserved.
45
Modulus Operator
■ The modulus operator, Mod, yields the remainder
after division.
■ Thus, 7 Mod 4 yields 3, and 17 Mod 5 yields 2.
■ This operator is used most commonly with
Integer operands.
■ The modulus operator can be used to discover
whether one number is a multiple of another.
 2009 Pearson Education, Inc. All rights reserved.
Integer Division and Modulus Examples
 2009 Pearson Education, Inc. All rights reserved.
 2009 Pearson Education, Inc. All rights reserved.
Variables and Arithmetic Operators
 2009 Pearson Education, Inc. All rights reserved.
Arithmetic Assignment Operators
 2009 Pearson Education, Inc. All rights reserved.
 2009 Pearson Education, Inc. All rights reserved.
The Scope and Lifetime of a Variable
■ Scope: indicates where the variable can be
used
■ Lifetime: indicates how long the variable
remains in memory
■ Variables can have class scope, procedure
scope, or block scope
■ A variable’s scope and lifetime are determined
by where you declare the variable
Variables declared in the form’s Declarations section have
class scope
Variables declared within a procedure have either
procedure scope or block scope
 2009 Pearson Education, Inc. All rights reserved.
Variables with Procedure Scope
■ Procedure-level variable: declared within a
procedure
Use the Dim keyword in the declaration
■ Procedure scope: only the procedure can use
the variable
With procedure-level scope, two procedures can each use
the same variable names
 2009 Pearson Education, Inc. All rights reserved.
Figure 3-14: The MainForm in the Sales Tax application
Figure 3-15: Examples of using procedure-level variables
 2009 Pearson Education, Inc. All rights reserved.
Variables with Class Scope
■ Class scope: variable can be used by all
procedures in the form
■ Class-level variable:
Declared in the form’s Declarations section
Use Private keyword in declaration
■ Class-level variables retain their values until the
application ends
 2009 Pearson Education, Inc. All rights reserved.
Figure 3-17: Example of using a class-level variable
 2009 Pearson Education, Inc. All rights reserved.
Static Variables
■ Static variable:
Procedure-level variable that remains in memory and
retains its value even after the procedure ends
Retains its value until the application ends (like a class-level
variable), but can only be used by the procedure in which
it is declared
■ A static variable has:
Same lifetime as a class-level variable
Narrower scope than a class-level variable
■ Declared using the Static keyword
 2009 Pearson Education, Inc. All rights reserved.
Static Variables
 2009 Pearson Education, Inc. All rights reserved.
Named Constants
■ Named constant: memory location whose
value cannot be changed while the application
is running
Declared using the Const keyword
Good programming practice to specify the data type as well
Many programmers use Pascal case for named constants
■ Literal type character: forces a literal constant
to assume a specific data type
■ Named constants help to document the
program code
 2009 Pearson Education, Inc. All rights reserved.
 2009 Pearson Education, Inc. All rights reserved.
Figure 3-20: Area Calculator application’s interface
Figure 3-21: Example of using a named constant
 2009 Pearson Education, Inc. All rights reserved.
Option Explicit, Option Infer,
and Option Strict
 2009 Pearson Education, Inc. All rights reserved.
Option Explicit, Option Infer,
and Option Strict (cont'd.)
■ Option Explicit On statement enforces that all
variables must be declared before being used
■ Undeclared variable: a variable that does not
appear in a declaration statement (such as Dim)
Is assigned a data type of Object
■ Misspelling a variable name can result in an
undeclared variable unless Option Explicit is
on
 2009 Pearson Education, Inc. All rights reserved.
Option Explicit, Option Infer,
and Option Strict (cont'd.)
■ Option Infer Off statement: ensures that every
variable is declared with a data type
 2009 Pearson Education, Inc. All rights reserved.
Option Explicit, Option Infer,
and Option Strict (cont'd.)
■ Option Strict On statement: ensures that values
cannot be converted from one data type to a
narrower data type, resulting in lost precision
■ Implicit type conversion: occurs when you
attempt to assign data of one type to a variable of
another type without explicitly attempting to
convert it
If converted to a data type that can store larger numbers, the
value is said to be promoted
If converted to a data type that can store only smaller
numbers, the value is said to be demoted. This can cause
truncation and loss of precision (not good!)
 2009 Pearson Education, Inc. All rights reserved.
 2009 Pearson Education, Inc. All rights reserved.
66
Debugging Errors
■ Debugging is the process of fixing errors in an
application.
■ The Visual Basic IDE contains a debugger that allows
you to analyze the behavior of your application.
■ There are two types of errors—compilation errors and
logic errors.
 2009 Pearson Education, Inc. All rights reserved.
67
Debugging 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. 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.
 2009 Pearson Education, Inc. All rights reserved.
68
Debugger Breakpoints
■ A breakpoint is a marker that can be set at any
executable line of code.
■ When application execution reaches a breakpoint,
execution pauses, allowing you to peek inside
your application and ensure that there are no logic
errors.
 2009 Pearson Education, Inc. All rights reserved.
69
Debugger Breakpoints
■ To insert a breakpoint in the IDE, either click inside the margin
indicator bar next to a line of code, or right click that line of
code and select Breakpoint > Insert Breakpoint
Fig. 6.16).
■ The application is said to be in break mode when the debugger
pauses the application’s execution.
Margin indicator bar
Breakpoints
Figure 6.16 | Setting two breakpoints.
 2009 Pearson Education, Inc. All rights reserved.
70
Debugger Breakpoints
■ After setting breakpoints in the code editor, select
Debug > Start Debugging to begin the
debugging process (Fig. 6.17, Fig. 6.18).
Figure 6.17 | Inventory application running.
Title bar displays (Debugging)
Figure 6.18 | Title bar of the IDE displaying (Debugging).
 2009 Pearson Education, Inc. All rights reserved.
71
Debugger Breakpoints
■ Application execution suspends at the first breakpoint,
and the IDE becomes the active window (Fig. 6.19).
The yellow arrow to the left of line 17 indicates that
this line contains the next statement to execute.
Yellow arrow
Next executable
statement
Breakpoints
Figure 6.19 | Application execution suspended at the first breakpoint.
 2009 Pearson Education, Inc. All rights reserved.
72
Debugger Breakpoints
■ To resume execution, select Debug > Continue
(or press F5).
■ Note that when you place your mouse pointer over the
variable name result, the value that the variable
stores is displayed in a Quick Info box (Fig. 6.20).
Quick Info box
displays variable
result’s value
Figure 6.20 | Displaying a variable value by placing the mouse pointer over a variable name.
 2009 Pearson Education, Inc. All rights reserved.
73
Debugger Breakpoints
■ Use the Debug > Continue command to complete
the application execution. When there are no more
breakpoints at which to suspend execution, the
application executes to completion (Fig. 6.21).
Figure 6.21 | Application output.
 2009 Pearson Education, Inc. All rights reserved.
Formatting Numeric Output
■ Formatting: specifying the number of decimal
places and any special characters to display
■ ToString method of a variable can be used to
format a number
■ FormatString argument: specifies the type of
formatting to use
■ Precision specifier: controls the number of
significant digits or zeros to the right of the decimal
point
 2009 Pearson Education, Inc. All rights reserved.
 2009 Pearson Education, Inc. All rights reserved.
Figure 3-39: The calcButton’s modified Click event procedure
 2009 Pearson Education, Inc. All rights reserved.