04.
Programming Basics for
VB (Part 2)
Outline
Assignment Operator – Short Form
Option Explicit
Variable Scope
Type Conversion
Rounding and Formatting
Exception Handling
Swapping
2
Assignment Operators – Short
Form
k = k + 2 can be written as k += 2
The semantics of
variable = variable op (expression)
is equivalent to
variable op= expression
Some "short-form" assignment operators
+= -= *= /= \= ^= &=
3
Assignment Operators – Short
Form
4
Be Careful!
j *= k + 3
is equivalent to
j = j * (k + 3)
rather than
j = j * k + 3
5
Option Explicit
Option Explicit forces variables to be
declared before using.
◦ The default value is “On” (we better not to change
it)
Option Explicit Off
Has to be the same as the filename
Public Class HelloForm
Private Sub PushButton_Click(sender As Object,
e As EventArgs) Handles PushButton.Click
integer1 = 45
MessageLabel.Text = integer1
End Sub
End Class
6
Scope of Variables
Visibility of a variable is its scope.
◦ Determine where the variable can be used
Scope may be (from the largest to the lowest)
1. Namespace (discuss later, not recommended)
Available to all procedures of all modules/classes in the project
2. Module level
Available to all procedures within that module/class (e.g.
HelloForm)
3. Local
Available only to the procedure in which it is declared
4. Block level (discuss later)
Available only in block of code inside a procedure where declared
7
Module Level
Declared inside a module/class (e.g. HelloForm) but outside any
procedures
Available to all procedures within that module/class
Public Class HelloForm
Dim integer1 As Integer = 45 Declare a module level variable
Private Sub PushButton_Click(sender As Object,
e As EventArgs) Handles PushButton.Click
MessageLabel.Text = integer1 No compile error
End Sub
Private Sub ExitButton_Click(sender As Object,
e As EventArgs) Handles ExitButton.Click
MessageBox.show(integer1) No compile error
Me.Close()
End Sub
End Class 8
Local Variable
Declared inside a procedure
It can only be used within that procedure but not “visible”
by other procedures
Public Class HelloForm
Private Sub PushButton_Click(sender As Object,
e As EventArgs) Handles PushButton.Click
Dim integer1 As Integer = 45 Declare a local variable
MessageLabel.Text = integer1
End Sub
Private Sub ExitButton_Click(ByVal sender As Object,
e As EventArgs) Handles ExitButton.Click
MessageBox.show(integer1) Compile error as the compiler
Me.Close()
does not know what integer1 is
End Sub
End Class
9
String vs. Number
In VB, a string of digits and a number are
different
A string is a sequence of characters
◦ E.g. “123.8” 5 characters
◦ We cannot directly perform arithmetic operations on
text strings
Before calculation, the text string has to be
converted into the corresponding number
◦ “123.8” 123.8 (number)
◦ “-18.8” -18.8 (number)
10
Implicit Conversion
Very often, VB performs the text-number
conversion automatically so that we can
still get the correct result
◦ Implicit conversion
11
Implicit Conversion
Private Sub CalculateButton_Click(sender As Object,
e As EventArgs) Handles CalculateButton.Click
OutputTextBox.Text = InputTextBox.Text * 3
End Sub
12
Explicit Conversion
On the other hand, we can also write the
code perform the conversion explicitly
◦ Explicit conversion
13
Explicit Conversion
Private Sub CalculateButton_Click(sender As Object,
e As EventArgs) Handles CalculateButton.Click
Dim num As Integer
num = Integer.Parse(InputTextBox.Text)
OutputTextBox.Text = num * 3
End Sub
14
Explicit Conversion
Use Parse() methods to convert the Text property to
its numeric form before it’s used in a calculation
Each numeric data type class has a Parse() method.
For example
◦ Dim i As Integer = Integer.Parse("20")
◦ Dim d As Decimal = Decimal.Parse(InputTextBox.Text)
Parse method returns a value that can be used in
calculations
15
Handling Exceptions
When we ask the users to input numbers for
calculations, things can go wrong
◦ For example, if the user enters nonnumeric data or simply
leaves the text box blank, the text-number conversion
(implicit or explicit) will cause run-time errors
Use structured exception handling to catch
errors before run-time errors occur
◦ Catching exceptions is referred to as error trapping
◦ Coding to handle exception is called error handling
16
Try/Catch Blocks
Enclose statements that might cause an
error within Try/Catch block
◦ If an exception occurs while statements in the Try
block are executing, the program control will be
transferred to the Catch Block immediately
Try
Dim i As Integer = Integer.Parse(InputTextBox.Text)
' Or simply InputTextBox.Text
MessageBox.Show(i)
MessageBox.Show("Bye")
Catch
MessageBox.Show("Invalid input.")
End Try
17
Try/Catch Blocks
One usage of Integer.Parse() is to check
whether the user entered an integer or a
number with decimals
◦ In the previous example, when the user enters 1.5,
it will display “Invalid input.”
◦ But if implicit conversion is used instead (i.e., no
Integer.Parse()), even when the user enters 1.5, it
will display “2” instead of “Invalid input.”
18
Try/Catch Blocks
Optionally, we can add ex As Exception
after Catch and then use ex.Message to
display the error message
Try
Dim i As Integer = Integer.Parse("Hello")
MessageBox.Show("This message will not appear")
Catch ex As Exception
' Display the error message
MessageBox.Show(ex.Message)
End Try
19
Conversion from Numbers to
Strings
Dim inputNumber As Integer
inputNumber = InputTextBox.Text
MessageLabel.Text = inputNumber number-to-text
Values assigned to string variables or Text properties must
be strings
In some cases, such a conversion is performed by VB
automatically (implicit conversion)
20
Conversion from Numbers to
Strings
To explicitly convert any numeric data type to
string, we can use the ToString() method
◦ MessageLabel.Text = inputNumber.ToString()
◦ ResultTextBox.Text = resultDecimal.ToString()
◦ IDString = IDInteger.ToString()
The ToString() method is implicitly called to
convert the number to a string
We can use the ToString() method for formatting
output (see later for details)
21
Option Strict
Option Strict (default is Off)
◦ If we set it to On
The following implicit conversions are not
allowed
1. From wider data types to narrower data types
E.g., Integer Short, or Double Integer
It may not be safe as the number can be too large
2. Between String and numeric data types (both directions)
It may not be safe to convert from a String to a numeric
data type
But implicit conversions from narrower data types to
wider data types are still allowed
Makes VB a strongly typed language like C++, Java, and
C#
22
23
Conversion between Numeric Data
Types
In VB, we can convert data from one numeric data
type to another
Some conversions can be performed implicitly
(automatically) and some we must specify explicitly
24
Conversion between Numeric Data
Types
Implicit conversion
◦ Automatically converts the value from a narrower data
type to a wider data type where no danger of losing
precision exists
Example:
◦ bigNumberDouble = smallNumberInteger
◦ This will not generate any error message, assuming
that both variables are properly declared
25
Conversion between Numeric Data
Types
However, to convert in the opposite direction
◦ smallNumberInteger = bigNumberDouble
◦ Rounding may occur (rounding towards even, more details
later)
◦ But if the integer variable is not large enough to hold the
double value, run-time errors will occur
◦ If the option strict is On
Compile errors will occur due to the implicit conversion from
a wider data type to a narrower data type
We need to use explicit conversion if we really want to do the
conversion (see next slide)
May result in run-time errors (similar to implicit conversion)
26
Conversion between Numeric Data
Types
Explicit conversion (casting)
◦ Uses methods of Convert class to convert between
data types
◦ Convert Class has methods that begin with “To” for
each of the data types
Examples
◦ Dim i as Integer = Convert.ToInt32(3.5)
Rounding may occur (rounding towards even)
◦ Dim d As Decimal = Convert.ToDecimal(integer1)
27
Conversion between Numeric Data
Types
Performing calculations with unlike data types
◦ resultValue = integerValue + doubleValue
◦ VB performs the calculations using the wider data type
◦ integerValue is converted by VB automatically to a
double type value before adding to doubleValue
◦ resultValue will store a double type value
◦ Example:
5 + 6.7
5.0 + 6.7
11.7
28
Rounding in VB
Rounding half up in mathematics
1.5 <= n < 2.5 2
2.5 <= n < 3.5 3
3.5 <= n < 4.5 4
VB: rounding to the nearest even (Banker’s rounding)
1.5 <= n <= 2.5 2
2.5 < n < 3.5 3
3.5 <= n <= 4.5 4
We have different results for rounding 2.5 (2 vs. 3) and
4.5 (4 vs. 5)
29
Rounding in VB
Decimal.Round() method returns a decimal result rounded to a specified number
of decimal positions
resultDecimal = Decimal.Round(decimalToRound, 2)
Round decimalToRound to 2 decimal places and store the result into
resultDecimal
Decimal Value to Number of Decimal Results
Round Positions
1.455 2 1.46
1.445 2 1.44
1.5 0 2
2.5 0 2
Implicit conversion, Convert methods, and Decimal.Round(), round a number to
the nearest even
◦ However, there is an exception for ToString() (see next page)
30
Formatting Data for Display
Recall that we can use ToString() method to explicitly
convert a numeric data to a string
DisplayTextBox.Text = numberInteger.ToString()
Format the data using formatting codes
◦ Specifies the use of dollar sign, percent sign, and
commas
◦ Specifies the number of digits that appear to right
of decimal point
Put formatting code
◦ Rounding half up is used here
DisplayTextBox.Text = numberInteger.ToString("N0")
31
Using Format Specifier
Codes
"N" code
◦ Number — String formatted with commas separating each
group of 3 digits, with 2 digits to the right of decimal point
"C" code
◦ Currency — String formatted with dollar sign, commas
separating each group of 3 digits, with 2 digits to the right
of decimal point
Can specify number of decimal positions
◦ Example: "C0" zero digits
32
Format Specifier Codes
Format Specifier Codes Name
C or c Currency
F or f Fixed-point
N or n Number
D or d Digits
P or p Percent
33
Format Specifier Code
Examples
Type Value Code Output
Decimal 1125.6744 "C" $1,125.67
Decimal 1125.6744 “N" 1,125.67
Decimal 1125.6744 "N0" 1,126
Decimal 1125.6744 “N3" 1,125.674
Decimal 1125.6744 “F3" 1125.674
Decimal 0.075 "P" 7.50%
Decimal 0.075 "P3" 7.500%
Decimal 0.075 “P0" 8%
34
Format Specifier Code
Examples
Type Value Code Output
Integer 123 "D6" 000123
Integer 123 "D2" 123
Integer -10 "C" ($10.00)
Integer -10 “N" -10.00
Integer -10 “D3" -010
35
Swapping Two Values
Private Sub SwapButton_Click(sender As Object,
e As EventArgs) Handles SwapButton.Click
InputTextBox1.Text = InputTextBox2.Text
InputTextBox2.Text = InputTextBox1.Text
End Sub
InputTextBox1: A
InputTextBox2: B
36
Swapping Two Values
Private Sub SwapButton_Click(sender As Object,
e As EventArgs) Handles SwapButton.Click
InputTextBox1.Text = InputTextBox2.Text
InputTextBox2.Text = InputTextBox1.Text
End Sub
InputTextBox1: A B
InputTextBox2: B B
37
Swapping Two Values
Private Sub SwapButton_Click(sender As Object,
e As EventArgs) Handles SwapButton.Click
InputTextBox1.Text = InputTextBox2.Text
InputTextBox2.Text = InputTextBox1.Text
End Sub
InputTextBox1: A B B
InputTextBox2: B B B
Fail
38
Swapping Two Values
Private Sub SwapButton_Click (sender As Object,
e As EventArgs) Handles SwapButton.Click
Dim tempStr As String
tempStr = InputTextBox1.Text
InputTextBox1.Text = InputTextBox2.Text
InputTextBox2.Text = tempStr
End Sub
InputTextBox1: A
InputTextBox2: B
tempStr: ""
39
Swapping Two Values
Private Sub SwapButton_Click (sender As Object,
e As EventArgs) Handles SwapButton.Click
Dim tempStr As String
tempStr = InputTextBox1.Text
InputTextBox1.Text = InputTextBox2.Text
InputTextBox2.Text = tempStr
End Sub
InputTextBox1: A A
InputTextBox2: B B
tempStr: "" A
40
Swapping Two Values
Private Sub SwapButton_Click (sender As Object,
e As EventArgs) Handles SwapButton.Click
Dim tempStr As String
tempStr = InputTextBox1.Text
InputTextBox1.Text = InputTextBox2.Text
InputTextBox2.Text = tempStr
End Sub
InputTextBox1: A A B
InputTextBox2: B B B
tempStr: "" A A
41
Swapping Two Values
Private Sub SwapButton_Click (sender As Object,
e As EventArgs) Handles SwapButton.Click
Dim tempStr As String
tempStr = InputTextBox1.Text
InputTextBox1.Text = InputTextBox2.Text
InputTextBox2.Text = tempStr
End Sub
InputTextBox1: A A B B
InputTextBox2: B B B A
tempStr: "" A A A
42
References and Readings
Visual Basic 2012 How to Program (6th
Edition)
◦ Paul Deitel, Harvery Deitel, and Abbey Deitel,
Pearson
◦ Chapter 3. Introduction to Visual Basic Programming
Programming in Visual Basic 2010
◦ Bradley and Millspaugh, McGraw-Hill
◦ Chapter 3. Variables, Constants, and Calculations
43