Chapter Four Decisions
Chapter Four Decisions
INTRODUCTION
Chapter 4 In-Class Project
In this chapter you will build a project that computes payroll information for hourly employees
of the VB University.
Employee Information Groupbox – application users type the employee name, ID, department
(where the employee works), hours worked, and pay rate into the controls.
The employee ID is a MaskedTextBox control – the social security number is the Mask property
setting.
For hourly employees, the hours worked (to the nearest 10th of an hour) and hourly pay rate are
entered into two TextBoxes.
The hours worked must be a number between 0 and 60 – the firm will not pay for more than 60
hours per pay period.
Benefits Groupbox – three radio button and three checkbox controls are used to capture information
about employee benefit options.
Employees can opt for the firm’s standard plan – 5% of their gross pay is deducted
from their check and placed in a special retirement account – employees opting for
this plan will be paid interest on their accumulated retirement deductions according to
the T-bills market.
Employees can participate in a 401A plan – 8% of their gross pay is deducted each pay
period and the firm will match this contribution – the money is managed by a local
firm that invests the money in mutual funds.
Medical insurance costs an hourly employee $37.75 per pay period through a group
health maintenance organization (HMO) plan.
Life insurance is provided at a fee of $18.35 per pay period through a special group
employee plan.
Payroll Information Groupbox – four TextBox controls (with ReadOnly = True, TabStop =
False, and TextAlign = Right) display output.
Gross Pay – this is the pay rate times the hours work. Employees working over 40
hours per week are paid 1.5 times their normal pay rate for all hours worked over 40
hours.
Federal Tax – the amount of federal tax due from an employee depends on the
employee's gross pay amount. The federal tax structure is discussed later in these notes.
Net Pay – computed as gross pay minus federal tax minus benefits.
Decision Structures and Commands
If Statements
An If statement implements branching logic based on a testable condition – example:
The left pane of this table shows pseudo code – a combination of VB and English to help
you organize program logic.
The right pane shows a program flowchart – a logic diagram that can also help you
organize program logic.
If Weather=Warm Then
Go golfing
The True branch corresponds to the keyword Then and the False branch corresponds to the
keyword Else in the pseudo code.
You can code an unlimited number of statements inside either the True or False
branches.
If <condition> Then
Else
(condition is false - do all of the actions
End If
The key word Then must appear on the same line as the word If.
The key words Else and End If must appear on lines by themselves.
The Else branch is optional (see example below). Only use an Else statement if there is
a False branch.
Visual Basic automatically indents 4 spaces inside the True and False branches to make
the statement easier to read.
It simplifies the coding because there is no need to convert a single or double data type to
decimal when performing calculations such as multiplying hours worked by the worker’s
pay rate.
Hours worked is measured to the 1/10th of an hour – decimal data can store many
significant digits to the right of the decimal point so no precision in data storage is lost.
Several of the calculations are rounded using the Decimal.Round method that requires a
decimal variable or expression (rather than a single or double) as the argument of the
Round method.
Comparisons must be made comparing like data types to like data types, for example:
Compare string to string (text), compare decimal to decimal, compare single to single.
If MedicalCheckBox.Checked Then
If MedicalCheckBox.Checked Then
'Checked the medical insurance checkbox
BenefitsCostDecimal += MEDICAL_RATE_DECIMAL
End If
GrossPayDecimal = Decimal.Round(HoursDecimal *
PayRateDecimal, 2)
Else
End If
Analyze the computation of gross pay for an overtime situation.
(40D * PayRateDecimal)
The hours worked over 40 hours is computed with this part of the formula:
(HoursDecimal – 40D)
The overtime pay due is computed with this part of the formula:
The Decimal.Round method rounds the gross pay to the nearest cent – the entire formula
for gross pay computation is coded inside of the Decimal.Round method.
VB Editor
The VB Editor tries to help you write If statements.
When in the code view window, if you type the keyword If and the condition to be tested, then
press Enter and the VB editor automatically adds the keywords Then and End If.
If you type EndIf with no space, the editor will correct this and add the required space.
If you type Else with a coding statement on the line, the editor will add a colon between Else
and the coding statement – the colon is a statement separator.
These three coding segments show illegal syntax, VB editor’s correction, and the preferred
syntax.
Illegal Syntax
RegularPayCheckBox.Checked = True
End If
RegularPayCheckBox.Checked = True
End If
Preferred Syntax
RegularPayCheckBox.Checked = True
Else
RegularPayCheckBox.Checked = False
End If
Characters are indicated under the Char column – their decimal and hexadecimal value
(numbering system base 16) equivalents are shown in the Dec and Hex columns.
The code column gives the ASCII equivalent of some special functions of the keyboard
such as the Bell (Hex 07) and a carriage return (CR – Hex 0D).
This is like an alphabetic comparison, but strings may also contain special characters.
All numbers that are part of strings are less than all letters (Hex values 48 – 57).
A blank space is less than all numbers, characters, and special characters (Hex value 20).
Some special characters are less than letters, but some are greater than letters.
Upper-case letters (Hex values 41 – 5A) are less than lower-case letters (Hex values 61 –
7A).
VB stores string characters in Unicode – this coding system stores all characters as 2 bytes each
to enable storage of all international languages (up to 65,536 unique character codes) – ANSI
uses only the first byte.
Which is Bigger?
Analyze this coding segment and determine which message box will display.
Name1String = "Donnie"
Name2String = "Doug"
Else
This does not change the actual data stored, simply how the data values are treated.
End If
The ToLower method is the opposite of ToUpper – all characters are treated as if they are
typed in lower-case letters.
Logical Operators
Logical operators are used to combine conditions. These are termed compound conditions.
The logical operators are as follows:
Or operator – If one condition or both conditions are True, the entire compound condition
evaluates to True. In this example, if a checkbox control named SalaryRadioButton is checked
or a second checkbox control named ContractRadioButton, then the worker is paid on a
monthly basis.
If SalaryRadioButton.Checked = True Or
ContractRadioButton.Checked = True Then
Else
And operator – Both conditions being combined must be True in order for the compound
condition to be True. In this example, if a TextBox control named HoursTextBox enabled
AND if the data in HoursTextBox is not numeric data, then this is a data error condition that
must be corrected before data can be processed.
Else
End If
Not operator – Negates a condition – if a condition is True, it is treated as False, and vice-
versa. In this example, an existence test is made for the existence of data in a TextBox control.
Else
End If
The Not operator can be confusing. You can rewrite the above coding segment by using the not
equal to comparison operator:
Else
You can also use reverse logic to rewrite the coding segment.
Else
End If
o If the first condition is False, the compound condition is treated as False and the
second condition is not evaluated.
o In this example, if the value in the HoursTextBox TextBox is not numeric, then
there is no need to test the second condition – in fact, if the value is not numeric,
testing the value to see if it falls within a numeric range would lead to an
exception error due to trying to compare non-numeric data with numeric values.
Else
HoursTextBox.Focus()
HoursTextBox.SelectAll()
End If
o If the first condition is True, the compound condition is treated as True and the
second condition is not evaluated.
o This is sort of a mirror-image of the AndAlso operator – sometimes you will use
one, sometimes the other depending upon how you choose to structure your
logic.
o In this example, the data in the HoursTextBox TextBox control is first evaluated
to see if it is numeric – if it is not then the condition evaluates to True – since Not
Numeric is False the second condition testing if the hours worked is less than 0D
or greater than 60D is not tested.
o Note that the two conditions cannot be reversed – you must test for numeric data
before testing to see if data is less than or equal to zero or greater than some
maximum value because if the data is not numeric, then the second condition
would cause an exception – you cannot compare non-numeric data to a number.
HoursTextBox.Focus()
HoursTextBox.SelectAll()
Else
End If
Xor operator – Termed the Exclusive Or operator.
o If one condition is True, the other must be False in order for the compound
condition to be treated as True overall.
o The Xor operator is rarely used in business applications—it is only useful where
situations are mutually exclusive.
Else
End If
This table summarizes the results of using the And, Or, AndAlso, OrElse, and Xor logical
operators to evaluate a compound condition that is comprised of two simple conditions. It also
summarizes the effect of the Not operator on any condition.
False -- True
In-Class Exercise
The pseudo code for the sub procedure is shown at a very high-level here in the form of remarks
statements. Each of the remarks may require multiple lines of code in order to accomplish the
task.
Try
Else
End If
Catch ex As Exception
End Try
End Sub
Missing Data Test – data values cannot be missing – this means a TextBox control cannot be
empty.
Numeric Data Test – numeric values must be tested to ensure they are numeric.
Reasonableness Test – values (usually numeric) must fall within a specified reasonable
range.
In this note set we use an If-ElseIf-Else-End If coding block to validate the contents of
TextBox, MaskedTextBox, and other data input controls. Rules about this coding block:
You can have as many additional ElseIf statements as needed to support the logic.
Only the If or a single ElseIf statement can execute.
This figure illustrates the logical approach taken for a data validation coding block for two
business rules. Can you redraw the diagram if there are three business rules to be tested?
If the name is missing, you can use a MessageBox.Show method to inform the
application user that the data is missing.
This code segment illustrates the coding logic for the click event of the ComputeButton
with data validation code added to validate the NameTextBox.
NameTextBox.Focus()
NameTextBox.SelectAll()
Else
Catch ex As Exception
End Try
End Sub
The above sub procedure uses an If-Else-End If coding block to compare the Text property of
the NameTextBox control to the VB enumerated value String.Empty.
The Trim method trims (deletes) leading and trailing blank characters – if the textbox
only contains spaces (blank characters) the Trim method results in the empty string.
If the TextBox is empty, a MessageBox displays an appropriate message – the focus is
set to the NameTextBox.
The SelectAll method highlights all text within a control such as a MaskedTextBox or
TextBox.
The Else branch is used to store all code for the Input-Process-Output model – the Else
branch is always used to store code to be processed if there are NO data validation
problems.
Note that the MessageBox statement inside the Else branch is only coded to demonstrate that the
data validation rules are met – this MessageBox statement must be removed later when you
begin the detailed coding of the Else branch.
Data entered into a control that displays the EmployeeID that has a Mask setting of SSN must be
a fixed length – additionally, the control cannot contain blank spaces.
EmployeeIDMaskedTextBox.Text.IndexOf(" ", 0, _
MessageBoxIcon.Error)
EmployeeIDMaskedTextBox.Focus()
EmployeeIDMaskedTextBox.SelectAll()
The first half of the complex condition uses the Length method to evaluate the string length.
o Again, the Trim method trims off leading and trailing blanks in case the value is
not complete, e.g., 123-45-44 (blank, blank).
The second half of the complex condition is evaluated if the string is 11 characters in length –
here the IndexOf method can search the string for the existence of any character (in this case a
blank space) within a specified portion of a string, e.g., 123-45-6 89 (blank is in the middle of
the string).
o The IndexOf method takes three arguments – the search character is specified
first – here it is a blank space within double-quote marks.
o The beginning position in the string is specified next – here the position 0
specifies to start the search with the first character.
EmployeeIDMaskedTextBox.Text.Length
o If the search character (a blank space) is NOT found, a value of -1 is returned by the
IndexOf method.
As additional business rules are validated, these are always coded as ElseIf statements
(and coding branches) – only the first business rule is coded with an If statement.
Try
NameTextBox.Focus()
NameTextBox.SelectAll()
EmployeeIDMaskedTextBox.Text.IndexOf(" ", 0, _
EmployeeIDMaskedTextBox.Focus()
EmployeeIDMaskedTextBox.SelectAll()
Else
Catch ex As Exception
End Sub
This code segment illustrates the updated coding logic for the ComputeButton click
event to validate the DepartmentTextBox.
Notice the validation by use of an additional ElseIf statement and placement of the
statement.
Try
NameTextBox.Focus()
NameTextBox.SelectAll()
ElseIf EmployeeIDMaskedTextBox.Text.Trim.Length <> 11
OrElse _
EmployeeIDMaskedTextBox.Text.IndexOf(" ", 0, _
EmployeeIDMaskedTextBox.Focus()
EmployeeIDMaskedTextBox.SelectAll()
DepartmentTextBox.Focus()
DepartmentTextBox.SelectAll()
Else
Catch ex As Exception
End Try
End Sub
Hours worked must be numeric and also fall within a specific valid range – zero to 60 hours.
The first part of the compound condition uses the IsNumeric function to determine if the
hours worked is a valid number (highlighted in yellow).
The second half of the compound condition tests if the parsed value of the TextBox is <=
0 or > 60 (highlighted in light blue).
HoursTextBox.Focus()
HoursTextBox.SelectAll()
An alternative to using the OrElse operator is to break the compound condition into two
separate, ElseIf statements.
The first ElseIf statement tests for a numeric value – if it is not numeric, a specific error message
is given.
The second ElseIf statement tests that the number is within the value range 0 to 60.
Notice that the order of the two validation tests is important – if you try to conduct the
reasonableness text before checking that hours is numeric, the ElseIf will throw an
FormatException.
This logic is considerably more complex – key learning point: learn to use the OrElse
operator.
HoursTextBox.Focus()
HoursTextBox.SelectAll()
ElseIf Decimal.Parse(HoursTextBox.Text,
Globalization.NumberStyles.Number) <= 0D Or
Decimal.Parse(HoursTextBox.Text,
Globalization.NumberStyles.Number) > 60D Then
HoursTextBox.Focus()
HoursTextBox.SelectAll()
The PayRateTextBox control must also be validated for numeric values and this is the final data
validation task for this application.
This test also uses the OrElse operator.
The reasonableness test here is simpler – the pay rate is only invalid if it is <= 0.
PayRateTextBox.Focus()
PayRateTextBox.SelectAll()
Add the code to text the hours worked and pay rate to the ComputeButton click event – the
coding procedure now looks like this:
Try
NameTextBox.SelectAll()
EmployeeIDMaskedTextBox.Text.IndexOf(" ", 0, _
EmployeeIDMaskedTextBox.Focus()
EmployeeIDMaskedTextBox.SelectAll()
DepartmentTextBox.Focus()
DepartmentTextBox.SelectAll()
HoursTextBox.Focus()
HoursTextBox.SelectAll()
ElseIf IsNumeric(PayRateTextBox.Text) = False OrElse
Decimal.Parse(PayRateTextBox.Text,
Globalization.NumberStyles.Currency) <= 0D Then
PayRateTextBox.Focus()
PayRateTextBox.SelectAll()
Else
Catch ex As Exception
End Try
End Sub
Try
'Display output
End If
Catch ex As Exception
End Try
End Sub
'Else
'End If
This computation uses a standard block If statement with both True and False branches.
'Try
' Convert TextBox values for hours worked and pay rate to
memory
' Else
' End If
'Catch
'End Try
Use the first pseudo code shown above and convert it to VB code. The solution is shown
here – note the location of the Else statement for the overall If statement that controls
data validation and IPO processing.
'Declare variables
Else
HoursDecimal = Decimal.Parse(HoursTextBox.Text,
Globalization.NumberStyles.Number)
PayRateDecimal = Decimal.Parse(PayRateTextBox.Text,
Globalization.NumberStyles.Currency)
GrossPayDecimal = Decimal.Round(HoursDecimal *
PayRateDecimal, 2)
End If
'Display output
GrossPayTextBox.Text = GrossPayDecimal.ToString("C2")
Prior to computing the value for GrossPayDecimal (a memory variable), the Text
property of the hours worked and pay rate TextBox controls are parsed and assigned to
memory variables.
You can optionally decide to declare constants for the numeric values 40D and 1.5D;
however, these are fixed in our society by law and so coding these values as constants is
probably not necessary.
First, delete the MessageBox statement that was temporarily added to the Else branch for
earlier testing of the validation rules.
Continue to use the break point at the beginning of the ComputeButton sub procedure
that you set earlier.
Run the program and enter data for which the results will be known, e.g., hourly worker
working 40 hours @ $10/hour.
Place the mouse pointer over a variable name or control property to examine the current
value at the time of execution and VB displays the current value of the variable.
The logic for computing taxes can be implemented as shown in this logic diagram.
If the gross pay is less than $985, then tax is computed at the 8% rate and control passes out of
the structure.
If gross pay is more than $985 but less than $2,450, then tax is computed at the 18% rate.
The last False branch has tax computed at the 28% rate.
Declare tax rate constants to store the tax rate as well as the break points (income levels)
as shown here. These can be coded as either module-level constants or as local
constants within the Compute button's click event. You may code these as local
constants as they are only used within this single sub procedure.
FederalTaxDecimal = Decimal.Round(TAX_RATE_08_DECIMAL *
GrossPayDecimal, 2)
FederalTaxDecimal = Decimal.Round(TAX_RATE_18_DECIMAL *
GrossPayDecimal, 2)
FederalTaxDecimal = Decimal.Round(TAX_RATE_28_DECIMAL *
GrossPayDecimal, 2)
End If
'Display output
FederalTaxTextBox.Text = FederalTaxDecimal.ToString("N")
Add the code required to compute and display federal income tax to your program.
Add FederalTaxDecimal to the Dim statement inside the sub procedure used to declare
decimal variables.
Add the code to compute federal tax due from the employee after computing the gross
pay.
Test the program: Run the program and enter data to test each tax bracket.
You might think to use the And logical operator to test the various checkbox combinations;
unfortunately, this approach becomes infeasible when the number of check box controls is large.
It is better to use simple If statements as shown in the solution given below.
The cost of each insurance plan on a per pay period basis is stored as a constant – declare
the constants as local or module-level, it does not matter – the example code uses local in
because the constants are only used in this single sub procedure.
Note the use of the += (plus equal) operator – this causes the benefit cost to accumulate.
. . .
'Benefit constants
If MedicalCheckBox.Checked Then
End If
If lifeCheckBox.Checked Then
End If
If DentalCheckBox.Checked Then
End If
BenefitsTextBox.Text = BenefitsCostDecimal.ToString("N")
Test the program: Run the program and enter data to test each insurance benefit.
Here you may be tempted to try to use the Or logical operator to test the various combinations,
but this approach is awkward and can become infeasible when the number of radio button
controls is large.
The best approach uses the If-ElseIf-Else-End If decision structure since only one of the
conditions (radio button checked) can be true.
The same BenefitsCostDecimal variable is used to add the cost of retirement benefits to
the already accumulated cost of insurance benefits in order to arrive at a total cost of
benefits (insurance + retirement) within the sub procedure.
The cost of the standard and 401A retirement plans on a per pay period basis is stored as
constants, either local module-level, it does not matter. For demonstration purposes,
constants are coded as module-level.
Note that since the cost of no retirement plan is zero, this doesn’t need to be coded.
The use of the += (plus equal) operator causes the cost to accumulate.
The cost of the retirement benefit is computed by multiplying the retirement percentage
by the gross pay value, and is rounded to the nearest penny.
'Benefit constants
. . .
Const RETIREMENT_STANDARD_DECIMAL As Decimal = 0.05D
If Retirement401ARadioButton.Checked Then
BenefitsCostDecimal +=
Decimal.Round(RETIREMENT_401A_DECIMAL* GrossPayDecimal, 2)
BenefitsCostDecimal +=
Decimal.Round(RETIREMENT_STANDARD_DECIMAL * GrossPayDecimal,
2)
Else
End If
'Display output
BenefitsTextBox.Text = BenefitsCostDecimal.ToString("N")
Test the program: Run the program and enter data to test each retirement benefit.
The solution is shown below along with the additional assignment statement to display the net
pay. Remember to add the NetPayDecimal variable to the Dim statement declaring all decimal
variables for the sub procedure.
. . .
GrossPayTextBox.Text = GrossPayDecimal.ToString("C")
federalTaxTextBox.Text = FederalTaxDecimal.ToString("N")
BenefitsTextBox.Text = BenefitsCostDecimal.ToString("N")
netPayTextBox.Text = NetPayDecimal.ToString("C")
Test the program: Run the program and enter data to test each to confirm that the net pay
computation is correct – use a calculator to validate the solution.
The entire ComputeButton click event coding solution is given at the end of this note
set.
The overall logic for most events that involve computing values where data must be valid in
order to compute the values is given in this pseudocode:
The large If-ElseIf-Else-End If statement is used to validate and process the data.
o The If and ElseIf branches are used to test if the business rule is INVALID.
o If a business rule is violated, display a message box, set the focus to the control
with invalid data, select any data within that control, then transfer overall program
control to the last End If statement.
o You may also need to use the Focus and SelectAll methods to set the focus to and
highlight the data in the form control that contains invalid data.
The Else branch is used to store all of the code used for Input-Process-Output-Other Tasks.
This branch can become very, very large—often 50 to 100 lines of code.
A correct solution will almost always have ABSOLUTELY NO CODE between the last End If
and the Catch statements.
There will be no code after the End Try statement except for the End Sub.
Try
'Input
'Process
'Output
'Other Tasks
End If
Catch ex As Exception
End Try
End Sub
You can use a Select Case statement to compute the federal income tax due instead of using an
If statement. The advantage of a Select Case instead of multiple If statements is that a Select
Case is often easier to read and code than multiple If statements.
The Select Case coding approach is shown here for a single variable named GrossPayDecimal.
The Case Else branch is optional and covers all other case values listings.
FederalTaxDecimal = Decimal.Round(TAX_RATE_08_DECIMAL
* GrossPayDecimal, 2)
FederalTaxDecimal = Decimal.Round(TAX_RATE_18_DECIMAL
* GrossPayDecimal, 2)
End Select
The Case Else branch is optional and is used when the various Case statements are not
completely exhaustive of all possible values for the object being evaluated.
You must use the keyword Is when using a comparison operator such as =, >=, or <=;
examples:
Else
End If
Select Case ValueDecimal
Case Else
End Select
To test for a value that falls within a range of constants, the keyword To is used;
example:
Case 25 To 72
Case 90 To 100
Else
End If
Select Case ValueDecimal
Case 25 To 72
Case 90 To 100
Case Else
End Select
If ValueDecimal = 15 Or ValueDecimal = 17 Or _
'Do something
Else
'Do alternative
End If
Select Case ValueDecimal
'Do something
Case Else
'Do alternative
End Select
To test a string value, include the literal value within double-quote marks; example:
Case Else
End Select
Replace the tax computation code with the SELECT CASE code above for computing federal
income tax to your program. Test the program again.
Test the program: Run the program and enter data to test each tax bracket.
If ButtonDialogResult = Windows.Forms.DialogResult.Yes
Then
Me.Close()
End If
End Sub
A dialog result variable named ButtonDialogResult is declared and set equal to the
MessageBox.Show method – dialog result variables store values representing a dialog
interface with the application user.
Program execution pauses while a MessageBox displays with the message, an
appropriate title bar and two buttons (Yes and No).
Test the program: Add the code to your project and test the Exit button.
NameTextBox.Clear()
EmployeeIDMaskedTextBox.Clear()
DepartmentTextBox.Clear()
HoursTextBox.Clear()
PayRateTextBox.Clear()
GrossPayTextBox.Clear()
FederalTaxTextBox.Clear()
BenefitsTextBox.Clear()
NetPayTextBox.Clear()
NoneRadioButton.Checked = True
MedicalCheckBox.Checked = False
LifeCheckBox.Checked = False
DentalCheckBox.Checked = False
NameTextBox.Focus()
End Sub
Combining Radio Button CheckedChanged
Events
An alternative way to program the cost of a benefit that is represented by radio button controls
is through the CheckedChanged event. Each radio button control can have a CheckedChanged
event, or a group of radio button controls can share the same CheckedChanged event as is
demonstrated here.
A CheckedChanged event is coded for one of the radio buttons (the button selected does
NOT matter).
The Handles clause is modified to handle the event for each additional retirement event
radio buttons (highlighted in yellow).
RetirementRateDecimal = 0D
RetirementRateDecimal = RETIREMENT_STANDARD_DECIMAL
RetirementRateDecimal = RETIREMENT_401A_DECIMAL
End Select
End Sub
The Handles clause is modified to handle the CheckedChanged event for each of the
status radio button controls as highlighted above in yellow.
o You simply type a comma at the end of an existing Handles clause and use
Intellisense to access the control/event combination that you also want this sub
procedure to handle.
o It does not matter which sub procedure you select initially – here the
NoneRadioButton radio button’s CheckedChanged event sub procedure was
selected.
A "generic" radio button object is created in memory with the Dim statement shown
here.
The CType (convert type) function is used to convert the sender object, which
represents the radio button selected by the application user from an "object" to a "radio
button" control and store it to the radio button object that exists in memory – this step is
necessary because the sender object does not actually exist until run time – trying to
reference sender as an object prior to this will result in an exception message known as
"late binding not allowed".
o The Name property of the memory radio button is evaluated to determine which
button has the Checked property changed.
Modify the program: Prior to testing you must complete these tasks:
Modify the Compute button control’s Click Event by Remarking out the code that
accumulates the cost of the retirement benefit (the If-ElseIf-Else-End If code), and by
deleting the declarations for the two retirement rate constants.
' BenefitsCostDecimal +=
Decimal.Round(RETIREMENT_401A_DECIMAL* GrossPayDecimal, 2)
' BenefitsCostDecimal +=
Decimal.Round(RETIREMENT_STANDARD_DECIMAL * GrossPayDecimal,
2)
'Else
'End If
Add a single line of code as shown here to accumulate the cost of the retirement benefit.
BenefitsCostDecimal += Decimal.Round(GrossPayDecimal *
RetirementRateDecimal, 2)
Test the program: Confirm that the cost of retirement benefit is still computed correctly.
Use the Debug.WriteLine method to write a value to the immediate window – this is useful
when you are working through a program line-by-line.
Example: Insert this code at the beginning of the Compute button's click sub procedure to write
information to the immediate window:
Clear the immediate window by right-clicking within the immediate window and choosing
Clear All.
Break All
Clicking the Break All icon on the Debug toolbar will cause execution to break when running a
program and will place you in debug mode. I haven't found this to be particularly useful – it is
often better to force a break point – it can be used when the program is stuck in an endless loop.
Break Points
Earlier in these notes you learned how to set a break point for a sub procedure – the Compute
Button's click event sub procedure – by clicking in the gray vertical bar on the left side of the
coding window (see the figure below).
As you learned earlier, you can check the current value of a variable or property (or any
expression) by putting the mouse pointer over the object.
Use the Step Over menu option (or debug toolbar icon or F8) to step line by line.
Use the Step Out (or debug toolbar icon or Ctrl+Shift+F8) to finish execution of the
current procedure.
Use the Stop Debugging option to end the run when you find the error.
Use the Continue option to run the program to the next natural break in execution where
the program waits for additional input or application actions.
You can toggle break points or clear all break points from the Debug menu.
Edit and Continue – During Debug mode, you can modify code to correct errors, then
press F5 (or Debug/Continue) to continue code execution for testing purposes.
Locals Windows
This window displays the values of all objects and variables that are within local scope at break
time.
Expand the Me entry to see the state of all of the form's controls. Note the current values
being modified are highlighted in red.
Autos Window
This window displays all variable and control contents referenced in the current statement and
three statements before/after the current statement.
Solution to In-Class Exercise
'Project: Ch04VBUniversity (Solution)
'D. Bock
'Today's Date
Try
'Benefit constants
NameTextBox.Focus()
NameTextBox.SelectAll()
EmployeeIDMaskedTextBox.Focus()
EmployeeIDMaskedTextBox.SelectAll()
MessageBox.Show("Department is required",
"Department Missing Error", MessageBoxButtons.OK,
MessageBoxIcon.Error)
DepartmentTextBox.Focus()
DepartmentTextBox.SelectAll()
HoursTextBox.Focus()
HoursTextBox.SelectAll()
PayRateTextBox.Focus()
PayRateTextBox.SelectAll()
Else
HoursDecimal = Decimal.Parse(HoursTextBox.Text,
Globalization.NumberStyles.Number)
PayRateDecimal =
Decimal.Parse(PayRateTextBox.Text,
Globalization.NumberStyles.Currency)
'Compute gross pay
GrossPayDecimal = Decimal.Round(HoursDecimal
* PayRateDecimal, 2)
GrossPayDecimal = Decimal.Round((40D *
PayRateDecimal) _
End If
FederalTaxDecimal =
Decimal.Round(TAX_RATE_08_DECIMAL * GrossPayDecimal, 2)
FederalTaxDecimal =
Decimal.Round(TAX_RATE_18_DECIMAL * GrossPayDecimal, 2)
FederalTaxDecimal =
Decimal.Round(TAX_RATE_28_DECIMAL * GrossPayDecimal, 2)
End Select
'Compute insurance benefits deduction
If MedicalCheckBox.Checked Then
BenefitsCostDecimal += MEDICAL_RATE_DECIMAL
'selected medical insurance
End If
If LifeCheckBox.Checked Then
BenefitsCostDecimal += LIFE_RATE_DECIMAL
'selected life insurance
End If
If DentalCheckBox.Checked Then
BenefitsCostDecimal += DENTAL_RATE_DECIMAL
'selected dental insurance
End If
' BenefitsCostDecimal +=
Decimal.Round(RETIREMENT_401A_DECIMAL * GrossPayDecimal, 2)
'ElseIf RetirementStandardRadioButton.Checked
Then
' BenefitsCostDecimal +=
Decimal.Round(RETIREMENT_STANDARD_DECIMAL * GrossPayDecimal, 2)
'Else
BenefitsCostDecimal +=
Decimal.Round(GrossPayDecimal * RetirementRateDecimal, 2)
NetPayDecimal = GrossPayDecimal -
FederalTaxDecimal - BenefitsCostDecimal
GrossPayTextBox.Text =
GrossPayDecimal.ToString("C")
FederalTaxTextBox.Text =
FederalTaxDecimal.ToString("N")
BenefitsTextBox.Text =
BenefitsCostDecimal.ToString("N")
NetPayTextBox.Text = NetPayDecimal.ToString("C")
Catch ex As Exception
End Try
End Sub
If ButtonDialogResult = Windows.Forms.DialogResult.Yes
Then
Me.Close()
End If
End Sub
NameTextBox.Clear()
EmployeeIDMaskedTextBox.Clear()
DepartmentTextBox.Clear()
HoursTextBox.Clear()
PayRateTextBox.Clear()
GrossPayTextBox.Clear()
FederalTaxTextBox.Clear()
BenefitsTextBox.Clear()
NetPayTextBox.Clear()
NoneRadioButton.Checked = True
MedicalCheckBox.Checked = False
LifeCheckBox.Checked = False
DentalCheckBox.Checked = False
NameTextBox.Focus()
End Sub
RetirementRateDecimal = 0D
RetirementRateDecimal =
RETIREMENT_STANDARD_DECIMAL
RetirementRateDecimal = RETIREMENT_401A_DECIMAL
End Select
End Sub
End Class
END OF NOTES