VBU Lesson Notes 3
VBU Lesson Notes 3
Coverage:
This chapter teaches you to write programs that involve the calculation of values for display
to a form. In order to calculate values, you will often need to compute intermediate values
and this will involve the storage of values to memory locations called variables. You will
learn how to declare variables to store different types of data, one of the naming conventions
used within industry, to convert text data to numeric data, to format output, and use Try-
Catch blocks to catch data processing exceptions (also termed errors). You will also use
message boxes to display messages to the application user.
In this chapter you build a project that computes information about textbook sales for the VB
University. The project form is shown below and uses some of the controls that you learned
in your earlier study of VB.
Input – Application users enter values into TextBoxes (and other controls such as
check boxes if such controls are used on a form). These values are input to the
program. The program must convert the values entered into the textboxes and store
the values to memory variables or locations in memory.
Process – The computer program includes code that processes the input values
stored in memory and produces output values, also stored in memory.
Output – The output memory values computed are displayed to read-only textbox
controls on the form. Either textbox controls (with the ReadOnly property set to
True) or label controls are used to display output information – the key is you do not
want the application user to be able to enter values into a control used to display
output – I prefer to use read-only textbox controls instead of labels.
Variables
Provide a means to store data values that are not stored in files.
Support the computation of values through their use in formulas in assignment
statements.
Represent locations in a computer's memory.
are assigned a unique name for reference when writing computer code
This figure illustrates the concept of a variable name associated with locations in random
access memory.
Values are stored to memory locations (represented by the rectangle).
The stored values can vary over time.
Each memory location is assigned a unique variable name that is used to reference
the location when you write a program.
Later you will learn how to name variables and allocate memory locations to the
storage of data.
Types of Data
VB provides numerous data types to allow programmers to optimize the use of computer
memory. Each data type is described in the table shown here. Note the:
Data type name.
Description of data stored.
Memory storage requirement in bytes.
Table 3.1
Most business applications primarily use String, Decimal, Single, and Integer data types.
Here are examples of data that may be stored to computer memory:
Customer Name – String – Stores alphabetic characters.
Social Security Number – String – Numbers that are not used in computations.
Customer Number – String – Numbers that are not used in computations.
Balance Due – Decimal – Used in calculations and often requires a decimal point to
separate dollars and cents.
Quantity in Inventory – Integer or Short – Selection depends on how large the
quantity in inventory will be, but the quantity is usually a whole number.
Sales Tax Rate – Single or Decimal – Used to store a percentage value; also used
for scientific calculations.
Naming Conventions
Naming variables and constants follows the Camel Casing naming convention that you
learned in your earlier chapter. Use the following guidelines:
1. Create meaningful names – do not name a variable or constant X or Y or XInteger.
Instead use names such as StudentNameString, CountStudentsInteger, and
AmountDueDecimal.
2. Avoid using abbreviations unless the abbreviation is standard and well-accepted
such as SSNString for storing social security number values.
3. Begin each name with an uppercase letter and capitalize each successive word in
the name.
4. Use mixed case (such as AmountDueDecimal) for variables – use Uppercase for
constant names (such as TAX_RATE_SINGLE).
Table 3.2
Dim statement – use this to declare variables and constants inside a procedure
these are local variables.
The Dim statement needs to specify a variable/constant name and data type.
o Specifying an initial value for a variable is optional.
o Constants must have an initial value specified.
o Examples:
You can also declare more than one variable in a Dim statement.
Declaring Constants
Declare constants with the Const statement.
Constants are similar to variables – constants are values that are stored to memory
locations; however, a constant cannot have its value change during program
execution – constant values are generally fixed over time.
Examples: sales tax rate or name of one of the states in the United States.
Examples:
String (text or character) constants are assigned values within the " " (double quote) marks.
This statement stores double-quote marks as part of the string – do this by typing two
double-quote marks together.
Numeric constants like those shown above do NOT use double-quote marks – just type the
numeric value numbers. Follow these rules for assigning numeric values to constants:
You can use numbers, a decimal point, and a plus (+) or minus (-) sign.
Do not include special characters such as a comma, dollar sign, or other special
characters.
Append one of these characters to the end of the numeric constant or variable to
denote a data type declaration. If you do not use these, a whole number is assumed
to be Integer and a fractional value is assumed to be Double.
Decimal D 40.45D
Double R 12576.877R
Integer I 47852I
Long L 9888444222L
Short S 2588S
Single F 0.0725F
This figure illustrates where to declare local versus module-level variables/constants. Later
you will learn to declare namespace and block variables and constants and when to use the
Public keyword in place of Private.
Key Points about Errors
If you name a module-level and local variable the same name, VB will create two
different variables! The local variable will exist within the procedure where it is
named, but the module-level variable will exist elsewhere in the code for the form.
This also applies to constants.
When you first declare a local variable, VB will underline the variable and tell you it is
"an unused local variable" – this is not really an error because the exception
message will go away automatically when you use the variable name in an
assignment statement.
CALCULATIONS
Calculations are performed with variables, constants, and object properties such as the Text
property of a TextBox.
Example #1 – this example shows you how to declare numeric variables then store values
to them from Textbox controls.
'Declare variables
Dim PriceDecimal As Decimal
Dim QuantityInteger As Integer
Example #2 – this example shows you how to declare numeric variables and store values to
them from Textbox controls using a single assignment statement in one step.
SubtotalTextBox.Text = SubtotalDecimal.ToString("N2")
SalesTaxTextBox.Text = SalesTaxDecimal.ToString("C2")
QuantityTextBox.Text = QuantityInteger.ToString("N0")
BiggerNumberDouble = SmallerNumberInteger
Explicit Conversion – this is also called Casting and is used to convert between
numeric data types that do not support implicit conversion. This table shows use of
the Convert method to convert one numeric data type to another numeric data type.
Note that fractional values are rounded when converting to integer.
Table 3.3
Summary Rules:
Use the Parse method to convert a string to a number or to parse the value in a
textbox control.
Use the Convert method to convert a type of number to a different type of number.
Arithmetic Operators
The arithmetic operators are the same as in many other programming languages. They
are:
+ Addition
- Subtraction
* Multiplication
/ Division
^ Exponentiation
\ Integer Division
Mod Modulus Division
Exponentiation – This raises a number to the specified power – the result produced is
data type Double. Example:
ValueSquaredDouble = NumberDecimal ^ 2
ValueCubedDouble = NumberDecimal ^ 3
Integer Division – Divide one integer by another leaving an integer result and discarding
the remainder, if any. Example:
If the variable MinutesInteger = 130, then this expression returns the value of 2
hours.
HoursInteger = MinutesInteger \ 60
Modulus Division – This returns the remainder of a division operation. Using the same
value for MinutesInteger = 500, this expression returns the value 20 minutes and can
be used to calculate the amount of overtime worked for an 8-hour work day.
Order of Precedence
The order of precedence for expressions that have more than one operation is the same as
for other programming languages.
The order of precedence is applied to an expression by evaluating the expression from left to
right for values within parentheses – within parentheses VB will process the expression from
left to right looking for an applying the exponentiation operator, then again from left to right
applying the multiplication and division operators, etc. This left to right application of
operators continues in pass-after-pass working down the order of precedence.
The plus symbol combined with the equal sign allows you to accumulate a value in a
memory variable. Examples:
TotalSalesDecimal += SaleAmountDecimal
is equivalent to the following – it means take the current value of TotalSalesDecimal and
add to it the value of SaleAmountDecimal and store it back to TotalSalesDecimal (it gets
bigger and BIGGER).
The minus symbol combined with the equal sign allows you to decrement or count
backwards. Examples:
CountInteger -= 1
is equivalent to
CountInteger = CountInteger - 1
QuantityInteger = QuantityTextBox.Text
With Option Strict On, you must write the following – VB will not
automatically convert the data from string to integer – you must parse the
data.:
QuantityInteger = Integer.Parse(QuantityTextBox.Text)
Use of Option Strict On is a good practice, but is not always followed in industry.
We will almost always use Option Strict On in our programs.
Place the command in your program after the general comments at the top of the
program as the first line of code as shown here.
'Project: Ch03VBUniversity
'D. Bock
'Today's Date
Option Strict On
Rounding Numbers
Use the Decimal.Round method to round decimal values to a desired number of positions
to the right of the decimal. Always specify the number of digits to round – the default is to
round to the nearest whole number. Always round when multiplying and dividing or when
using exponentiation as these operations can result in rounding errors. Simple subtraction
and addition do not require rounding. Examples:
SalesTaxDecimal = Decimal.Round(SALES_TAX_RATE_DECIMAL *
AmountSoldDecimal, 2)
SalesTaxDecimal =
Decimal.Round(Convert.ToDecimal(SubtotalDecimal *
SALES_TAX_RATE_SINGLE), 2)
Data to be formatted for output will often use the ToString method you learned earlier.
Additional examples are shown here for your reference in completing programming
assignments:
Example #1: This shows formatting a decimal value to string for display in a textbox control
– the output is formatted as currency (dollar sign, commas, 2 decimal points – the default is
to format numeric output with 2 digits to the right of the decimal point).
SalesTaxTextBox.Text = SalesTaxDecimal.ToString("C")
Example #2: This shows formatting as currency, but with no digits to the right of the
decimal point.
TotalDueTextBox.Text = TotalDueDecimal.ToString("C0")
Example #3: This formats the output as a number with two digits to the right of the decimal
and with one or more commas as appropriate – sometimes you will not want to display a
currency symbol.
TotalDueTextBox.Text = TotalDueDecimal.ToString("N0")
Older versions of VB used functions to format output – these are still widely used and are
provided here for your reference if you find them in other textbooks.
FormatCurrency Function – This function displays output formatted as dollars and cents.
The default is a dollar sign, appropriate commas, and two digits to the right of the decimal.
This formats a value stored in memory named BalanceDueDecimal and displays it to the
TextBox control named BalanceDueTextBox. Remember, TextBox controls store string
values. Example:
BalanceDueTextBox.Text = FormatCurrency(BalanceDueDecimal)
AmountTextBox.Text = FormatNumber(AmountDouble)
AmountTextBox.Text = FormatNumber(AmountDouble,3)
FormatPercent Function – This function displays output formatted as a percent – it multiples the
argument by 100, adds a percent sign, and rounds to two decimal places. Example:
PercentFinishedTextBox.Text = FormatPercent(FinishedSingle)
Input: Start by entering remarks to play the logic of the procedure. Here is an example:
'Declare variables
End Sub
Do NOT try to start by coding the variables needed. Instead, each time you use a variable in
an assignment statement, you then declare the variable as necessary.
Begin by converting the PriceTextBox control's Text property value to a decimal
value in memory.
An appropriate variable name is PriceDecimal for the memory variable.
This causes you to need to also declare the variable. Your code now looks like this.
'Declare variables
Dim PriceDecimal As Decimal
You can also combine the above two statements into a single statement if you desire.
Now write an assignment statement to convert the Quantity TextBox control's Text property
to an integer value in memory. You will need another variable. Your code now looks like
this:
'Declare variables
Dim PriceDecimal As Decimal
Dim QuantityInteger As Integer
Alternatively, you can combine the above four statements into two statements.
Process: You will need variables to store intermediate values that will eventually be
displayed to the output TextBox controls. Examine the form. You'll see that the values are
all currency so you'll use the decimal data type.
Write the assignment statement to compute the subtotal (price multiplied by quantity).
You might use the variable name SubtotalDecimal to store the subtotal value in
memory.
Also update the Dim statement listing that declares decimal variables.
Computing the Sales Tax: Sales tax is charged on the subtotal at the rate of 7.25%. This
requires the following actions:
Declare a constant of data type single named SALES_TAX_RATE_SINGLE with
the value 7.25%.
Write an assignment statement that will compute the sales tax due and assign the
value to a memory variable named SalesTaxDecimal.
Update the Dim statement to add SalesTaxDecimal to the declaration list.
Use the Decimal.Round and Convert.ToDecimal methods to treat the expression
as a decimal value and to round to the nearest penny.
'Sales tax = sales tax rate times the subtotal minus discount
amount
SalesTaxDecimal =
Decimal.Round(Convert.ToDecimal(SubtotalDecimal *
SALES_TAX_RATE_SINGLE), 2)
Computing the Total Due: The total due is the formula: subtotal + sales tax. The total
due value is stored to a memory variable named TotalDueDecimal. Add this variable to the
Dim statement earlier in the sub procedure.
'Total due = the subtotal minus discount amount plus sales tax
TotalDueDecimal = SubtotalDecimal + SalesTaxDecimal
… Go to the top of sub procedure and declare the TotalDueDecimal variable (you can add it
to the existing Dim statement).
Output: Store the values from the memory variables to the Text property of the output
TextBox controls.
This code is straight-forward assignment statements, but requires formatting the
output (if desired) to appear in currency format.
No new variables are needed.
The default number of digits to the right of the decimal is 2 so you do not need to
specify C2 or N2.
You need to specify the use of specific text in the message box title bar. You can add a
graphic icon and button(s) to the message box. For now use the OK button; you will learn
other buttons in a later module.
Each parameter is separated by a comma. The parameters are shown in this general
format:
Try/Catch Blocks – The Try-Catch block is a coding technique used to catch exceptions –
this is called Exception Handling. The general format is as follows:
Try
'Place all of the code that you want to execute for the sub
procedure here.
'You can have lots of statements here.
Catch [Optional VariableName As ExceptionType]
'Place statements for action to take when
'an exception occurs.
'You can also have lots of statements here.
[Finally] 'This part is optional
'Place statements to always execute before the end
'of the Try block.
'You can also have lots of statements here.
End Try
Example:
Try
QuantityInteger = Integer.Parse(QuantityTextBox.Text,
Globalization.NumberStyles.Number)
PriceDecimal = Decimal.Parse(PriceTextBox.Text,
Globalization.NumberStyles.Currency)
. . . other code goes here to complete the processing
Catch ex As Exception
MessageBox.Show("Error in either Book Price or Quantity
Purchased", "Data Entry Error", MessageBoxButtons.OK,
MessageBoxIcon.Error)
End Try
In-Class Exercise
Modify the ComputeButton click event sub procedure to handle exceptions.
Add a Try-Catch block to catch errors if the application user enters invalid numeric
data.
Use a MessageBox statement to display the appropriate message.
Note the indentation used to aid in the readability of the code is automatically added
by VB.
Go to the first line within the ComputeButton sub procedure. Begin by typing the word Try
and pressing the Enter key. VB will add the following coding outline automatically.
Catch ex As Exception
End Try
Now highlight and drag/drop (or cut/paste) all of the code within the sub procedure that you
wrote earlier and paste this inside the Try portion of the Try-Catch block. Your code now
looks like this:
Catch ex As Exception
MessageBox.Show("Error in either Book Price or Quantity
Purchased", "Data Entry Error", MessageBoxButtons.OK,
MessageBoxIcon.Error)
PriceTextBox.Focus()
End Try
End Sub
Notice that all of the code that you want to execute will ALWAYS go inside the Try portion of
the Try-Catch block.
Note the addition of code above inside the Catch portion of the Try-Catch block to display
the exception message.
Note that the focus is set to the PriceTextBox control, although the error may be in
the quantity purchased.
In the next chapter you will learn how to determine which TextBox has the invalid
data.
Enabling and Disabling Controls
Controls such as buttons can be enabled and disabled (grayed out) through the Enabled
property.
A typical approach is to have the Reset button disabled on startup of the system. When the
Compute button is clicked and the calculations are displayed, the Reset command button is
enabled at that time.
'Enable/disable buttons
ComputeButton.Enabled = False
ResetButton.Enabled = True
'Enable/disable buttons
End Sub
Now write the code to perform the required tasks. You should have mastered this
from your previous exercises. Using the With-End With statement reduces the
amount of typing required.
Sums – programs often need to sum up numbers. For example, a cash register program
that sums up the amount due for a sale at a grocery store. In this case we are computing a
total by adding the cost of an item purchased to the total amount for every item (total of
the sale).
Counts – sometimes there is a need to count how many times something happens. Your
code usually counts by one each time, adding one to a memory variable.
Suppose that we need to display the total quantity of books sold along with the total dollar
value of sales and the average value of each book sold, then display these values with in a
MessageBox. This next section explains how to proceed.
Summing the Total Sales and Counting the Number of Books Sold
Because the total sales and count of books sold must be saved after every execution of the
Compute button's click event sub procedure, you need to declare two module-level variables
to store these values. The scope needs to be at the module-level for these values in order
to retain their value as long as the program is executing.
'Project: Ch03VBUniversity
'D. Bock
'Today's Date
Option Strict On
Each time the application user clicks the Compute Button your program must accumulate
the TotalQuantityInteger and TotalSalesDecimal values with the assignment statements
shown here. These statements can be added to the code for the Compute Button after the
code that enables/disables buttons.
Calculating an Average
Calculating an average by dividing a sum of some value by the count of the number of times
a value occurred.
Exceptions have properties used to determine the object causing the error (Source
property), location of the exception in your code (Stack-Trace property), type of exception,
and cause (Message property).
You can have multiple Catch blocks in a Try-Catch coding block to handle different
exceptions; but only ONE Catch block will execute—the first one with a matching exception.
This table lists just a few of the exceptions you can trap.
Table 3.6
Exception Description
FormatException Failure of data conversion for numeric data through use of
Integer.Parse, or some similar conversion.
InvalidCastException Failure to conversion operation caused by loss of significant
digits or some other illegal conversion.
ArithmeticException Calculation error such as divide by zero.
OutOfMemoryExceptio Not enough memory to create an object.
n
Exception The generic "catch all" exception.
Now you have learned the concepts and techniques needed to complete your next
programming assignment. Happy Computing!
Solution
'Project: Ch03VBUniversity
'D. Bock
'Today's Date
Option Strict On
'Declare variables
Dim SubtotalDecimal, SalesTaxDecimal, TotalDueDecimal As
Decimal
Catch ex As Exception
MessageBox.Show("Error in either Book Price or Quantity
Purchased", "Data Entry Error", MessageBoxButtons.OK,
MessageBoxIcon.Error)
PriceTextBox.Focus()
End Try
End Sub
'Enable/disable buttons
ComputeButton.Enabled = True
ResetButton.Enabled = False
End Class