04. Programming Basics for VB (Part 2)
04. Programming Basics for VB (Part 2)
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
+= -= *= /= \= ^= &=
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
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
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
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
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
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()
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
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
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
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()
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
32
Format Specifier Codes
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
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
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
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
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
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