All Chapter Exercise of VB

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 50

'Ch01VBUniversity

'D. Bock
'Today's Date
'Illustrates displaying information to read-only TextBox
'controls by clicking Button controls

Public Class StudentInfo

Private Sub Display1Button_Click(ByVal sender As


System.Object, ByVal e As System.EventArgs) Handles
Display1Button.Click
'Display information for the first student
NameTextBox.Text = "Douglas Bock"
MajorTextBox.Text = "Computer Management & Information
Systems"
End Sub

Private Sub Display2Button_Click(ByVal sender As


System.Object, ByVal e As System.EventArgs) Handles
Display2Button.Click
'Display information for the second student
NameTextBox.Text = "Jill Unverzagt"
MajorTextBox.Text = "Computer Management & Information
Systems"
End Sub

Private Sub Display3Button_Click(ByVal sender As


System.Object, ByVal e As System.EventArgs) Handles
Display3Button.Click
'Display information for the third student
NameTextBox.Text = "John Meisel"
MajorTextBox.Text = "Economics"
End Sub

Private Sub ResetButton_Click(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles ResetButton.Click
'Reset the form by clearing the TextBox controls
NameTextBox.Clear()
MajorTextBox.Clear()
End Sub

Private Sub PrintButton_Click(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles PrintButton.Click
'Print the form to a print preview window
'Assign a PrintAction option
PrintForm1.PrintAction =
Printing.PrintAction.PrintToPrevie
'Print the form
PrintForm1.Print()
End Sub

Private Sub ExitButton_Click(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles ExitButton.Click
'Exit the application by closing it
Me.Close()
End Sub

End Class

End of Notes.
'Project: Ch02VBUniversity
'D. Bock
'Today's Date

Public Class StudentInfo

'Module-level variables/constants
Private GrayBackGroundColor As Color

Private Sub DisplayButton_Click(ByVal sender As


System.Object, ByVal e As System.EventArgs) Handles
DisplayButton.Click
'Store output message to the output textbox using
implicit line continuation
OutputTextBox.Text =
"My name: " & NameTextBox.Text & ControlChars.NewLine
&
"Major: " & MajorTextBox.Text & ControlChars.NewLine
&
"Local phone: " & PhoneMaskedTextBox.Text
End Sub

Private Sub ResetButton_Click(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles ResetButton.Click
'Clear the input and output TextBox and MaskedTextBox
controls -
'This code shows use of the Clear method, String.Empty
value, and
'empty double quote marks
NameTextBox.Clear()
MajorTextBox.Text = String.Empty
PhoneMaskedTextBox.Clear()
OutputTextBox.Text = ""
'Reset the form's BackColor to gray
'and ForeColor to black
GrayRadioButton.Checked = True
BlackRadioButton.Checked = True

'Reset the message display CheckBox control to checked


MessageCheckBox.Checked = True

'Turn on the sun and turn off the snow


SunPictureBox.Visible = True
SnowPictureBox.Visible = False

'Set focus to first TextBox


NameTextBox.Focus()
End Sub

Private Sub ExitButton_Click(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles ExitButton.Click
'Exit the form
Me.Close()
End Sub

Private Sub SnowPictureBox_Click(ByVal sender As


System.Object, ByVal e As System.EventArgs) Handles
SnowPictureBox.Click
'Turn the snow into the sun
SnowPictureBox.Visible = False
SunPictureBox.Visible = True
End Sub

Private Sub SunPictureBox_Click(ByVal sender As


System.Object, ByVal e As System.EventArgs) Handles
SunPictureBox.Click
'Turn the sun into the snow
SnowPictureBox.Visible = True
SunPictureBox.Visible = False
End Sub

Private Sub GrayRadioButton_CheckedChanged(ByVal sender As


System.Object, ByVal e As System.EventArgs) Handles
GrayRadioButton.CheckedChanged
'Set the backcolor of the form to the default gray
Me.BackColor = GrayBackGroundColor
End Sub
Private Sub RedRadioButton_CheckedChanged(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
RedRadioButton.CheckedChanged
'Set the backcolor of the form
Me.BackColor = Color.Red
End Sub

Private Sub BlueRadioButton_CheckedChanged(ByVal sender As


System.Object, ByVal e As System.EventArgs) Handles
BlueRadioButton.CheckedChanged
'Set the backcolor of the form
Me.BackColor = Color.Blue
End Sub

Private Sub GreenRadioButton_CheckedChanged(ByVal sender As


System.Object, ByVal e As System.EventArgs) Handles
GreenRadioButton.CheckedChanged
'Set the backcolor of the form
Me.BackColor = Color.Green
End Sub

Private Sub WhiteRadioButton_CheckedChanged(ByVal sender As


System.Object, ByVal e As System.EventArgs) Handles
WhiteRadioButton.CheckedChanged
'Set form's text color
Me.ForeColor = Color.White
End Sub

Private Sub BlackRadioButton_CheckedChanged(ByVal sender As


System.Object, ByVal e As System.EventArgs) Handles
BlackRadioButton.CheckedChanged
'Set form's text color
Me.ForeColor = Color.Black
End Sub

Private Sub MessageCheckBox_CheckedChanged(ByVal sender As


System.Object, ByVal e As System.EventArgs) Handles
MessageCheckBox.CheckedChanged
'Make the OutputTextBox and OutputLabel invisible
OutputTextBox.Visible = MessageCheckBox.Checked
OutputLabel.Visible = MessageCheckBox.Checked
End Sub

Private Sub StudentInfo_Load(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles MyBase.Load
'Assign background color to module-level variable
GrayBackGroundColor = Me.BackColor
End Sub

Private Sub RichButton_Click(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles RichButton.Click
'Display information from Rich TextBox Contents.rtf file
to the RichTextBox
RichTextBox1.LoadFile("RichTextBoxContents.rtf")
End Sub

End Class

'Project: Ch03VBUniversity
'D. Bock
'Today's Date

Option Strict On

Public Class Books


'Declare module-level variables and constants
Private TotalQuantityInteger As Integer
Private TotalSalesDecimal As Decimal

Private Sub ComputeButton_Click(ByVal sender As


System.Object, ByVal e As System.EventArgs) Handles
ComputeButton.Click
Try
'Declare constants
'7.25 percent sales tax rate
Const SALES_TAX_RATE_SINGLE As Single = 0.0725

'Declare variables
Dim SubtotalDecimal, SalesTaxDecimal, TotalDueDecimal
As Decimal

'Declare variables and convert values from


'textbox controls to memory
Dim PriceDecimal As Decimal =
Decimal.Parse(PriceTextBox.Text,
Globalization.NumberStyles.Currency)
Dim QuantityInteger As Integer =
Integer.Parse(QuantityTextBox.Text,
Globalization.NumberStyles.Number)

'Process - Compute values


'Subtotal = price times the quantity of books
SubtotalDecimal = PriceDecimal * QuantityInteger
'Sales tax = sales tax rate times the subtotal
SalesTaxDecimal =
Decimal.Round(Convert.ToDecimal(SubtotalDecimal *
SALES_TAX_RATE_SINGLE), 2)

'Total due = subtotal plus sales tax


TotalDueDecimal = SubtotalDecimal + SalesTaxDecimal

'Display output formatted as currency


SubtotalTextBox.Text = SubtotalDecimal.ToString("C")
SalesTaxTextBox.Text = SalesTaxDecimal.ToString("N")
TotalDueTextBox.Text = TotalDueDecimal.ToString("C")

'Other tasks to code


'Enable/disable buttons
ComputeButton.Enabled = False
ResetButton.Enabled = True

'Accumulate total sales and total books sold.


TotalQuantityInteger += QuantityInteger
TotalSalesDecimal += TotalDueDecimal

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

Private Sub ResetButton_Click(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles ResetButton.Click
'Clear the text box controls
BookTitleTextBox.Clear()
ISBNTextBox.Clear()
PriceTextBox.Clear()
QuantityTextBox.Clear()
SubtotalTextBox.Clear()
SalesTaxTextBox.Clear()
TotalDueTextBox.Clear()

'Enable/disable buttons
ComputeButton.Enabled = True
ResetButton.Enabled = False

'Set the focus to the book title text box control


BookTitleTextBox.Focus()
End Sub

Private Sub ExitButton_Click(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles ExitButton.Click
'Close the form
Me.Close()
End Sub

Private Sub TotalsButton_Click(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles TotalsButton.Click
Try
'Display the total sales, total books sold,
'and average book value in a message box.
Dim AverageSaleDecimal As Decimal = TotalSalesDecimal
/ TotalQuantityInteger
Dim MessageString As String = "Total Sales: " &
TotalSalesDecimal.ToString("C") & ControlChars.NewLine & "Total
Books Sold: " & TotalQuantityInteger.ToString("N0") &
ControlChars.NewLine & "Average Book Value: " &
AverageSaleDecimal.ToString("C")

MessageBox.Show(MessageString, "Totals and Averages",


MessageBoxButtons.OK, MessageBoxIcon.Information)

Catch exArithmeticException As ArithmeticException


MessageBox.Show("No books have been sold yet", "Zero
Sales Message", MessageBoxButtons.OK, MessageBoxIcon.Information)
Catch ex As Exception
MessageBox.Show("Unexpected Error-inform the system
administrator", "Unknown Error in Totals Button",
MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub

End Class
'Project: Ch04VBUniversity (Solution)
'D. Bock
'Today's Date

Public Class Payroll


'Module level variable/constant declarations

'Declare retirement benefit constants


Const RETIREMENT_STANDARD_DECIMAL As Decimal = 0.05D
Const RETIREMENT_401A_DECIMAL As Decimal = 0.08D
Private RetirementRateDecimal As Decimal
Private Sub ComputeButton_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
ComputeButton.Click
Try
'Declare variables and constants
Dim HoursDecimal, PayRateDecimal, GrossPayDecimal,
FederalTaxDecimal, BenefitsCostDecimal, NetPayDecimal As Decimal

'Declare constant used in this sub procedure


'Tax rate constants
Const TAX_RATE_08_DECIMAL As Decimal = 0.08D
Const TAX_RATE_18_DECIMAL As Decimal = 0.18D
Const TAX_RATE_28_DECIMAL As Decimal = 0.28D
Const TAX_LEVEL_08_DECIMAL As Decimal = 985D
Const TAX_LEVEL_18_DECIMAL As Decimal = 2450D

'Benefit constants
Const MEDICAL_RATE_DECIMAL As Decimal = 35.75D
Const LIFE_RATE_DECIMAL As Decimal = 18.35D
Const DENTAL_RATE_DECIMAL As Decimal = 4D

'Enforce data validation rules


If NameTextBox.Text.Trim = String.Empty Then
'Required employee name is missing
MessageBox.Show("Name is required", "Name Missing
Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
NameTextBox.Focus()
NameTextBox.SelectAll()
ElseIf EmployeeIDMaskedTextBox.MaskCompleted = False
Then
'Required employee ID is not complete
MessageBox.Show("Employee ID is not complete",
"Employee ID Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
EmployeeIDMaskedTextBox.Focus()
EmployeeIDMaskedTextBox.SelectAll()
ElseIf DepartmentTextBox.Text.Trim = String.Empty
Then
'Required department is missing
MessageBox.Show("Department is required",
"Department Missing Error", MessageBoxButtons.OK,
MessageBoxIcon.Error)
DepartmentTextBox.Focus()
DepartmentTextBox.SelectAll()
ElseIf IsNumeric(HoursTextBox.Text) = False OrElse
(Decimal.Parse(HoursTextBox.Text,
Globalization.NumberStyles.Number) <= 0D Or
Decimal.Parse(HoursTextBox.Text,
Globalization.NumberStyles.Number) > 60D) Then
'Hours must be numeric and within allowable range
MessageBox.Show("Hours worked must be a number
between 0 and 60", "Hours Value Error", MessageBoxButtons.OK,
MessageBoxIcon.Error)
HoursTextBox.Focus()
HoursTextBox.SelectAll()
ElseIf IsNumeric(PayRateTextBox.Text) = False OrElse
Decimal.Parse(PayRateTextBox.Text,
Globalization.NumberStyles.Currency) <= 0D Then
'Pay rate must be numeric and greater than zero
MessageBox.Show("Pay rate worked must be a number
and greater than zero.", "Pay Rate Value Error",
MessageBoxButtons.OK, MessageBoxIcon.Error)
PayRateTextBox.Focus()
PayRateTextBox.SelectAll()
Else
'Data rules are all valid -- Use IPO model to
process data
'Parse textbox values to memory variables
HoursDecimal = Decimal.Parse(HoursTextBox.Text,
Globalization.NumberStyles.Number)
PayRateDecimal =
Decimal.Parse(PayRateTextBox.Text,
Globalization.NumberStyles.Currency)

'Compute gross pay


If HoursDecimal <= 40D Then 'pay only regular
time
GrossPayDecimal = Decimal.Round(HoursDecimal
* PayRateDecimal, 2)
Else 'pay regular + overtime
GrossPayDecimal = Decimal.Round((40D *
PayRateDecimal) _
+ ((HoursDecimal - 40D) * PayRateDecimal
* 1.5D), 2)
End If

'Compute federal tax


Select Case GrossPayDecimal
Case Is <= TAX_LEVEL_08_DECIMAL '8% tax
bracket
FederalTaxDecimal =
Decimal.Round(TAX_RATE_08_DECIMAL * GrossPayDecimal, 2)
Case Is <= TAX_LEVEL_18_DECIMAL '18% tax
bracket
FederalTaxDecimal =
Decimal.Round(TAX_RATE_18_DECIMAL * GrossPayDecimal, 2)
Case Else '28% tax bracket
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

''Remark out this part to test use of the


CheckedChanged event to
''set the retirement rate
''Compute retirement benefits deduction
'If Retirement401ARadioButton.Checked Then
' BenefitsCostDecimal +=
Decimal.Round(RETIREMENT_401A_DECIMAL * GrossPayDecimal, 2)
'ElseIf RetirementStandardRadioButton.Checked
Then
' BenefitsCostDecimal +=
Decimal.Round(RETIREMENT_STANDARD_DECIMAL * GrossPayDecimal, 2)
'Else
' 'No charge for not taking retirement benefit
'End If

'Use the retirement rate set in the


CheckedChanged event
'for the retirement radio button controls
BenefitsCostDecimal +=
Decimal.Round(GrossPayDecimal * RetirementRateDecimal, 2)

'Compute the net pay – no need to round because


'all values are already rounded
NetPayDecimal = GrossPayDecimal -
FederalTaxDecimal - BenefitsCostDecimal
'Display output – this shows all four outputed
values
GrossPayTextBox.Text =
GrossPayDecimal.ToString("C")
FederalTaxTextBox.Text =
FederalTaxDecimal.ToString("N")
BenefitsTextBox.Text =
BenefitsCostDecimal.ToString("N")
NetPayTextBox.Text = NetPayDecimal.ToString("C")
End If 'matches If statement for validating data
Catch ex As Exception
MessageBox.Show("Unexpected error: " &
ControlChars.NewLine & ex.Message, "Compute Button Error",
MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub

Private Sub ExitButton_Click(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles ExitButton.Click
'Close the form if the system user responds Yes
Dim MessageString As String = "Do you want to close the
form?"
Dim ButtonDialogResult As DialogResult =
MessageBox.Show(MessageString, "Quit?", MessageBoxButtons.YesNo,
MessageBoxIcon.Question, MessageBoxDefaultButton.Button2)
If ButtonDialogResult = Windows.Forms.DialogResult.Yes
Then
Me.Close()
End If
End Sub

Private Sub ResetButton_Click(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles ResetButton.Click
'Clear all textbox controls
NameTextBox.Clear()
EmployeeIDMaskedTextBox.Clear()
DepartmentTextBox.Clear()
HoursTextBox.Clear()
PayRateTextBox.Clear()
GrossPayTextBox.Clear()
FederalTaxTextBox.Clear()
BenefitsTextBox.Clear()
NetPayTextBox.Clear()

'Reset retirement benefits status to none


NoneRadioButton.Checked = True
'Uncheck benefits checkboxes
MedicalCheckBox.Checked = False
LifeCheckBox.Checked = False
DentalCheckBox.Checked = False

'Set focus to name textbox


NameTextBox.Focus()
End Sub

Private Sub NoneRadioButton_CheckedChanged(ByVal sender As


System.Object, ByVal e As System.EventArgs) Handles
NoneRadioButton.CheckedChanged,
Retirement401ARadioButton.CheckedChanged,
RetirementStandardRadioButton.CheckedChanged
'Create a radio button in memory and store the values of
sender to it
Dim CheckedRadioButton As RadioButton = CType(sender,
RadioButton)

'Use Select Case to evaluate the name of the radio button


'to decide which controls to enable/disable
Select Case CheckedRadioButton.Name
Case "NoneRadioButton" 'Cost is zero
RetirementRateDecimal = 0D
Case "RetirementStandardRadioButton" 'Standard rate
RetirementRateDecimal =
RETIREMENT_STANDARD_DECIMAL
Case "Retirement401ARadioButton" '401A rate
RetirementRateDecimal = RETIREMENT_401A_DECIMAL
End Select
End Sub

End Class
'Project: Ch04VBUniversity (Solution)
'D. Bock
'Today's Date

Public Class Payroll


'Module level variable/constant declarations

'Declare retirement benefit constants


Const RETIREMENT_STANDARD_DECIMAL As Decimal = 0.05D
Const RETIREMENT_401A_DECIMAL As Decimal = 0.08D
Private RetirementRateDecimal As Decimal
Private Sub ComputeButton_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
ComputeButton.Click
Try
'Declare variables and constants
Dim HoursDecimal, PayRateDecimal, GrossPayDecimal,
FederalTaxDecimal, BenefitsCostDecimal, NetPayDecimal As Decimal

'Declare constant used in this sub procedure


'Tax rate constants
Const TAX_RATE_08_DECIMAL As Decimal = 0.08D
Const TAX_RATE_18_DECIMAL As Decimal = 0.18D
Const TAX_RATE_28_DECIMAL As Decimal = 0.28D
Const TAX_LEVEL_08_DECIMAL As Decimal = 985D
Const TAX_LEVEL_18_DECIMAL As Decimal = 2450D

'Benefit constants
Const MEDICAL_RATE_DECIMAL As Decimal = 35.75D
Const LIFE_RATE_DECIMAL As Decimal = 18.35D
Const DENTAL_RATE_DECIMAL As Decimal = 4D

'Enforce data validation rules


If NameTextBox.Text.Trim = String.Empty Then
'Required employee name is missing
MessageBox.Show("Name is required", "Name Missing
Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
NameTextBox.Focus()
NameTextBox.SelectAll()
ElseIf EmployeeIDMaskedTextBox.MaskCompleted = False
Then
'Required employee ID is not complete
MessageBox.Show("Employee ID is not complete",
"Employee ID Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
EmployeeIDMaskedTextBox.Focus()
EmployeeIDMaskedTextBox.SelectAll()
ElseIf DepartmentTextBox.Text.Trim = String.Empty
Then
'Required department is missing
MessageBox.Show("Department is required",
"Department Missing Error", MessageBoxButtons.OK,
MessageBoxIcon.Error)
DepartmentTextBox.Focus()
DepartmentTextBox.SelectAll()
ElseIf IsNumeric(HoursTextBox.Text) = False OrElse
(Decimal.Parse(HoursTextBox.Text,
Globalization.NumberStyles.Number) <= 0D Or
Decimal.Parse(HoursTextBox.Text,
Globalization.NumberStyles.Number) > 60D) Then
'Hours must be numeric and within allowable range
MessageBox.Show("Hours worked must be a number
between 0 and 60", "Hours Value Error", MessageBoxButtons.OK,
MessageBoxIcon.Error)
HoursTextBox.Focus()
HoursTextBox.SelectAll()
ElseIf IsNumeric(PayRateTextBox.Text) = False OrElse
Decimal.Parse(PayRateTextBox.Text,
Globalization.NumberStyles.Currency) <= 0D Then
'Pay rate must be numeric and greater than zero
MessageBox.Show("Pay rate worked must be a number
and greater than zero.", "Pay Rate Value Error",
MessageBoxButtons.OK, MessageBoxIcon.Error)
PayRateTextBox.Focus()
PayRateTextBox.SelectAll()
Else
'Data rules are all valid -- Use IPO model to
process data
'Parse textbox values to memory variables
HoursDecimal = Decimal.Parse(HoursTextBox.Text,
Globalization.NumberStyles.Number)
PayRateDecimal =
Decimal.Parse(PayRateTextBox.Text,
Globalization.NumberStyles.Currency)

'Compute gross pay


If HoursDecimal <= 40D Then 'pay only regular
time
GrossPayDecimal = Decimal.Round(HoursDecimal
* PayRateDecimal, 2)
Else 'pay regular + overtime
GrossPayDecimal = Decimal.Round((40D *
PayRateDecimal) _
+ ((HoursDecimal - 40D) * PayRateDecimal
* 1.5D), 2)
End If

'Compute federal tax


Select Case GrossPayDecimal
Case Is <= TAX_LEVEL_08_DECIMAL '8% tax
bracket
FederalTaxDecimal =
Decimal.Round(TAX_RATE_08_DECIMAL * GrossPayDecimal, 2)
Case Is <= TAX_LEVEL_18_DECIMAL '18% tax
bracket
FederalTaxDecimal =
Decimal.Round(TAX_RATE_18_DECIMAL * GrossPayDecimal, 2)
Case Else '28% tax bracket
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

''Remark out this part to test use of the


CheckedChanged event to
''set the retirement rate
''Compute retirement benefits deduction
'If Retirement401ARadioButton.Checked Then
' BenefitsCostDecimal +=
Decimal.Round(RETIREMENT_401A_DECIMAL * GrossPayDecimal, 2)
'ElseIf RetirementStandardRadioButton.Checked
Then
' BenefitsCostDecimal +=
Decimal.Round(RETIREMENT_STANDARD_DECIMAL * GrossPayDecimal, 2)
'Else
' 'No charge for not taking retirement benefit
'End If

'Use the retirement rate set in the


CheckedChanged event
'for the retirement radio button controls
BenefitsCostDecimal +=
Decimal.Round(GrossPayDecimal * RetirementRateDecimal, 2)

'Compute the net pay – no need to round because


'all values are already rounded
NetPayDecimal = GrossPayDecimal -
FederalTaxDecimal - BenefitsCostDecimal
'Display output – this shows all four outputed
values
GrossPayTextBox.Text =
GrossPayDecimal.ToString("C")
FederalTaxTextBox.Text =
FederalTaxDecimal.ToString("N")
BenefitsTextBox.Text =
BenefitsCostDecimal.ToString("N")
NetPayTextBox.Text = NetPayDecimal.ToString("C")
End If 'matches If statement for validating data
Catch ex As Exception
MessageBox.Show("Unexpected error: " &
ControlChars.NewLine & ex.Message, "Compute Button Error",
MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub

Private Sub ExitButton_Click(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles ExitButton.Click
'Close the form if the system user responds Yes
Dim MessageString As String = "Do you want to close the
form?"
Dim ButtonDialogResult As DialogResult =
MessageBox.Show(MessageString, "Quit?", MessageBoxButtons.YesNo,
MessageBoxIcon.Question, MessageBoxDefaultButton.Button2)
If ButtonDialogResult = Windows.Forms.DialogResult.Yes
Then
Me.Close()
End If
End Sub

Private Sub ResetButton_Click(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles ResetButton.Click
'Clear all textbox controls
NameTextBox.Clear()
EmployeeIDMaskedTextBox.Clear()
DepartmentTextBox.Clear()
HoursTextBox.Clear()
PayRateTextBox.Clear()
GrossPayTextBox.Clear()
FederalTaxTextBox.Clear()
BenefitsTextBox.Clear()
NetPayTextBox.Clear()

'Reset retirement benefits status to none


NoneRadioButton.Checked = True
'Uncheck benefits checkboxes
MedicalCheckBox.Checked = False
LifeCheckBox.Checked = False
DentalCheckBox.Checked = False

'Set focus to name textbox


NameTextBox.Focus()
End Sub

Private Sub NoneRadioButton_CheckedChanged(ByVal sender As


System.Object, ByVal e As System.EventArgs) Handles
NoneRadioButton.CheckedChanged,
Retirement401ARadioButton.CheckedChanged,
RetirementStandardRadioButton.CheckedChanged
'Create a radio button in memory and store the values of
sender to it
Dim CheckedRadioButton As RadioButton = CType(sender,
RadioButton)

'Use Select Case to evaluate the name of the radio button


'to decide which controls to enable/disable
Select Case CheckedRadioButton.Name
Case "NoneRadioButton" 'Cost is zero
RetirementRateDecimal = 0D
Case "RetirementStandardRadioButton" 'Standard rate
RetirementRateDecimal =
RETIREMENT_STANDARD_DECIMAL
Case "Retirement401ARadioButton" '401A rate
RetirementRateDecimal = RETIREMENT_401A_DECIMAL
End Select
End Sub

End Class
'Project: Ch05VBUniversity (Solution)
'D. Bock
'Today's Date

Option Strict On

Public Class Payroll

#Region " Module level variable and constant declarations "

'Module level variable/constant declarations


Private RetirementRateDecimal As Decimal

#End Region

#Region " File Menu Events "


Private Sub ExitButton_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles ExitButton.Click, ExitToolStripMenuItem1.Click
'Close the form if the system user responds Yes
Dim MessageString As String = "Do you want to close the form?"
Dim ButtonDialogResult As DialogResult =
MessageBox.Show(MessageString, "Quit?", MessageBoxButtons.YesNo,
MessageBoxIcon.Question, MessageBoxDefaultButton.Button2)
If ButtonDialogResult = Windows.Forms.DialogResult.Yes Then
Me.Close()
End If
End Sub

Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
'Call Exit Button Click event
ExitButton.PerformClick()
End Sub

Private Sub ColorToolStripMenuItem_Click(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles ColorToolStripMenuItem.Click
'Change the form's back color property.
'Stores current form color to the control's Color property.
'Display the Color Component, and save the new color
'to the form's BackColor property.
ColorDialog1.Color = Me.BackColor
ColorDialog1.ShowDialog()
Me.BackColor = ColorDialog1.Color
MenuStrip1.BackColor = ColorDialog1.Color
End Sub

Private Sub FontToolStripMenuItem_Click(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles FontToolStripMenuItem.Click
'Change the font used for the entire form.
'Store current font to the control's Font property.
'Display the Font Component, and save the new font
'to the form's controls.
FontDialog1.Font = Me.Font
FontDialog1.ShowDialog()
Me.Font = FontDialog1.Font
MenuStrip1.Font = FontDialog1.Font
End Sub

Private Sub ColorToolStripMenuItem1_Click(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles ColorToolStripMenuItem1.Click
'Change color of object
'Send color to dialog box
ColorDialog1.Color = ContextMenuStrip1.SourceControl.ForeColor
ColorDialog1.ShowDialog()

'Display new color


ContextMenuStrip1.SourceControl.ForeColor = ColorDialog1.Color
End Sub

#End Region

#Region " Actions Menu Events "


Private Sub ComputeButton_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles ComputeButton.Click, ComputeToolStripMenuItem.Click,
ComputeToolStripMenuItem1.Click
Try
'Call ValidData function to validate business rules
If ValidData() Then
'Declare variables and constants
Dim HoursDecimal, PayRateDecimal, GrossPayDecimal,
FederalTaxDecimal, BenefitsCostDecimal, NetPayDecimal As Decimal

'Parse textbox values to memory variables


HoursDecimal = Decimal.Parse(HoursTextBox.Text,
Globalization.NumberStyles.Number)
PayRateDecimal = Decimal.Parse(PayRateTextBox.Text,
Globalization.NumberStyles.Currency)

'Call function ComputeGrossPay


GrossPayDecimal = ComputeGrossPay()

'Call function ComputeFederalTax


FederalTaxDecimal = ComputeFederalTax(GrossPayDecimal)

'Call function ComputeBenefitsDeduction


BenefitsCostDecimal =
ComputeBenefitsDeduction(GrossPayDecimal)

'Compute the net pay – no need to round because


'all values are already rounded
NetPayDecimal = GrossPayDecimal - FederalTaxDecimal -
BenefitsCostDecimal

'Display output – this shows all four outputed values


GrossPayTextBox.Text = GrossPayDecimal.ToString("C")
FederalTaxTextBox.Text = FederalTaxDecimal.ToString("N")
BenefitsTextBox.Text = BenefitsCostDecimal.ToString("N")
NetPayTextBox.Text = NetPayDecimal.ToString("C")
End If 'matches If statement for validating data
Catch ex As Exception
MessageBox.Show("Unexpected error: " & ControlChars.NewLine &
ex.Message, "Compute Button Error", MessageBoxButtons.OK,
MessageBoxIcon.Error)
End Try
End Sub

Private Sub ResetForm()


'Clear all textbox controls
NameTextBox.Clear()
EmployeeIDMaskedTextBox.Clear()
DepartmentTextBox.Clear()
HoursTextBox.Clear()
PayRateTextBox.Clear()
GrossPayTextBox.Clear()
FederalTaxTextBox.Clear()
BenefitsTextBox.Clear()
NetPayTextBox.Clear()
'Reset retirement benefits status to none
NoneRadioButton.Checked = True

'Uncheck benefits checkboxes


MedicalCheckBox.Checked = False
LifeCheckBox.Checked = False
DentalCheckBox.Checked = False

'Set focus to name textbox


NameTextBox.Focus()
End Sub

Private Sub ResetButton_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles ResetButton.Click
'This is the click event for the ResetButton control.
'Call ResetForm sub procedure to prepare
'for the next employee to have pay computed.
ResetForm()
End Sub

Private Sub ResetFormToolStripMenuItem_Click(ByVal sender As


System.Object, ByVal e As System.EventArgs) Handles
ResetFormToolStripMenuItem.Click
'This is the click event for the main menu ResetForm option.
'Call ResetForm sub procedure to prepare
'for the next employee to have pay computed.
ResetForm()
End Sub

Private Sub ResetFormToolStripMenuItem1_Click(ByVal sender As


System.Object, ByVal e As System.EventArgs) Handles
ResetFormToolStripMenuItem1.Click
'This is the click event for the context menu ResetForm option.
'Call ResetForm sub procedure to prepare
'for the next employee to have pay computed.
ResetForm()
End Sub

#End Region

#Region " Help Menu and Miscellaneous Events "

Private Sub NoneRadioButton_CheckedChanged(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles NoneRadioButton.CheckedChanged,
Retirement401ARadioButton.CheckedChanged,
RetirementStandardRadioButton.CheckedChanged
'Declare retirement benefit constants
Const RETIREMENT_STANDARD_DECIMAL As Decimal = 0.05D
Const RETIREMENT_401A_DECIMAL As Decimal = 0.08D

'Create a radio button in memory and store the values of sender to it


Dim CheckedRadioButton As RadioButton = CType(sender, RadioButton)

'Use Select Case to evaluate the name of the radio button


'to decide which controls to enable/disable
Select Case CheckedRadioButton.Name
Case "NoneRadioButton" 'Cost is zero
RetirementRateDecimal = 0D
Case "RetirementStandardRadioButton" 'Standard rate
RetirementRateDecimal = RETIREMENT_STANDARD_DECIMAL
Case "Retirement401ARadioButton" '401A rate
RetirementRateDecimal = RETIREMENT_401A_DECIMAL
End Select
End Sub

Private Sub AboutToolStripMenuItem_Click(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles AboutToolStripMenuItem.Click
'Display about message box
Dim MessageString As String = "Programmed by Dr. Douglas Bock" &
ControlChars.NewLine & "Today's Date/Time: " & Date.Now.ToString
Dim TitleString As String = "About the Payroll Application"

'Display output message


MessageBox.Show(MessageString, TitleString, MessageBoxButtons.OK,
MessageBoxIcon.Information)
End Sub

#End Region

#Region " Function Procedures "

Private Function ComputeGrossPay() As Decimal


'Parse textbox values to memory variables
Dim HoursDecimal As Decimal = Decimal.Parse(HoursTextBox.Text,
Globalization.NumberStyles.Number)
Dim PayRateDecimal As Decimal = Decimal.Parse(PayRateTextBox.Text,
Globalization.NumberStyles.Currency)

'Gross pay is computed and returned by assigning the value


'to the name of the function
If HoursDecimal <= 40D Then 'pay only regular time
ComputeGrossPay = Decimal.Round(HoursDecimal * PayRateDecimal, 2)
Else 'pay regular + overtime
ComputeGrossPay = Decimal.Round((40D * PayRateDecimal) +
((HoursDecimal - 40D) * PayRateDecimal * 1.5D), 2)
End If
End Function

Private Function ComputeFederalTax(ByVal GrossPayDecimal As Decimal) As


Decimal
'Tax rate constants
Const TaxRate08Decimal As Decimal = 0.08D
Const TaxRate18Decimal As Decimal = 0.18D
Const TaxRate28Decimal As Decimal = 0.28D
Const TaxLevel08Decimal As Decimal = 985D
Const TaxLevel18Decimal As Decimal = 2450D

'Declare variables used within the function


Dim FederalTaxDecimal As Decimal

'Compute amount of tax based on the amount of pay


Select Case GrossPayDecimal
Case Is <= TaxLevel08Decimal '8% tax bracket
FederalTaxDecimal = Decimal.Round(TaxRate08Decimal *
GrossPayDecimal, 2)
Case Is <= TaxLevel18Decimal '18% tax bracket
FederalTaxDecimal = Decimal.Round(TaxRate18Decimal *
GrossPayDecimal, 2)
Case Else '28% tax bracket
FederalTaxDecimal = Decimal.Round(TaxRate28Decimal *
GrossPayDecimal, 2)
End Select

'Return a value
Return FederalTaxDecimal
End Function

Private Function ComputeBenefitsDeduction(ByVal GrossPayDecimal As


Decimal) As Decimal
'Benefit constants
Const MedicalRateDecimal As Decimal = 35.75D
Const LifeRateDecimal As Decimal = 18.35D
Const DentalRateDecimal As Decimal = 4D

'Declare variables used within the function


Dim BenefitsCostDecimal As Decimal

'Compute insurance benefits deduction


If MedicalCheckBox.Checked Then
BenefitsCostDecimal += MedicalRateDecimal 'selected medical
insurance
End If
If LifeCheckBox.Checked Then
BenefitsCostDecimal += LifeRateDecimal 'selected life insurance
End If
If DentalCheckBox.Checked Then
BenefitsCostDecimal += DentalRateDecimal 'selected dental
insurance
End If

'Use the retirement rate set in the CheckedChanged event


'for the retirement radio button controls
BenefitsCostDecimal += Decimal.Round(GrossPayDecimal *
RetirementRateDecimal, 2)

'Return cost of benefits


Return BenefitsCostDecimal
End Function

Private Function ValidData() As Boolean


'Assume the data is not valid
ValidData = False

'Enforce data validation rules


If NameTextBox.Text = String.Empty Then
'Required employee name is missing
MessageBox.Show("Name is required", "Name Missing Error",
MessageBoxButtons.OK, MessageBoxIcon.Error)
NameTextBox.Focus()
ElseIf EmployeeIDMaskedTextBox.Text.Trim.Length <> 11 OrElse
EmployeeIDMaskedTextBox.Text.IndexOf(" ", 0,
EmployeeIDMaskedTextBox.Text.Length) <> -1 Then
'Required employee ID is not long enough or is not complete
MessageBox.Show("Employee ID is not complete", "Employee ID
Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
EmployeeIDMaskedTextBox.Focus()
EmployeeIDMaskedTextBox.SelectAll()
ElseIf DepartmentTextBox.Text = String.Empty Then
'Required department is missing
MessageBox.Show("Department is required", "Department Missing
Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
DepartmentTextBox.Focus()
ElseIf IsNumeric(HoursTextBox.Text) = False OrElse
(Decimal.Parse(HoursTextBox.Text, Globalization.NumberStyles.Number) <= 0D Or
Decimal.Parse(HoursTextBox.Text, Globalization.NumberStyles.Number) > 60D)
Then
'Hours must be numeric and within allowable range
MessageBox.Show("Hours worked must be a number between 0 and 60",
"Hours Value Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
HoursTextBox.Focus()
HoursTextBox.SelectAll()
ElseIf IsNumeric(PayRateTextBox.Text) = False OrElse
Decimal.Parse(PayRateTextBox.Text, Globalization.NumberStyles.Currency) <= 0D
Then
'Pay rate must be numeric and greater than zero
MessageBox.Show("Pay rate worked must be a number and greater than
zero.", "Pay Rate Value Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
PayRateTextBox.Focus()
PayRateTextBox.SelectAll()
Else
'Data rules are all valid
ValidData = True
End If
End Function

#End Region

End Class
This solution shows the Ch07VBUniversity project code.

'Project: Ch07VBUniversity (Solution)


'D. Bock
'Today's Date

Option Strict On

Public Class Employee

Private Sub AddDepartmentToolStripMenuItem_Click(ByVal sender


As System.Object, ByVal e As System.EventArgs) Handles
AddDepartmentToolStripMenuItem.Click
'Add department text property to combo box listing
Dim FoundBoolean As Boolean = False
Dim IndexInteger As Integer = 0

Do Until FoundBoolean = True Or IndexInteger =


DepartmentComboBox.Items.Count
If DepartmentComboBox.Text.Trim.ToUpper =
DepartmentComboBox.Items(IndexInteger).ToString.Trim.ToUpper Then
FoundBoolean = True
Else
'Add 1 to index value
IndexInteger += 1
End If
Loop 'Loop back and try again

'Now decide whether to add item or not


If FoundBoolean = False And DepartmentComboBox.Text.Trim
<> String.Empty Then

DepartmentComboBox.Items.Add(DepartmentComboBox.Text.Trim)
Else
MessageBox.Show("Duplicate or Invalid Department
Name", "Duplicate Data Error", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation)
DepartmentComboBox.Focus()
DepartmentComboBox.SelectAll()
End If
End Sub

Private Sub AddEmployeeToolStripMenuItem_Click(ByVal sender


As System.Object, ByVal e As System.EventArgs) Handles
AddEmployeeToolStripMenuItem.Click
'Add a new employee to the ListBox if Valid
If ValidData Then
'Build the string to add
Dim NewEmployeeString As String =
EmployeeNameTextBox.Text & ", " & TitleComboBox.Text & ", " &
DepartmentComboBox.Text & ", " & SalaryTextBox.Text

'Add string to ListBox


EmployeeListBox.Items.Add(NewEmployeeString)

'Clear the form - ready to add another employee


EmployeeNameTextBox.Clear()
TitleComboBox.SelectedIndex = -1
DepartmentComboBox.SelectedIndex = -1
DepartmentComboBox.Text = String.Empty
SalaryTextBox.Clear()
'Set focus
EmployeeNameTextBox.Focus()
End If
End Sub

Private Sub ClearEmployeeListToolStripMenuItem_Click(ByVal


sender As System.Object, ByVal e As System.EventArgs) Handles
ClearEmployeeListToolStripMenuItem.Click
'Use response variable to capture user response
Dim ResponseDialogResult As DialogResult =
MessageBox.Show("Clear employee listing Y/N?", "Yes or No",
MessageBoxButtons.YesNo, MessageBoxIcon.Question,
MessageBoxDefaultButton.Button2)

'Test to confirm whether to clear listing


If ResponseDialogResult = Windows.Forms.DialogResult.Yes
Then
EmployeeListBox.Items.Clear()
End If
End Sub

Private Sub ResetEmployeeToolStripMenuItem_Click(ByVal sender


As System.Object, ByVal e As System.EventArgs) Handles
ResetEmployeeToolStripMenuItem.Click
'Clear text box controls
EmployeeNameTextBox.Clear()
SalaryTextBox.Clear()

'Unselect title and department combo box controls and


'set Text property to empty string
TitleComboBox.SelectedIndex = -1
DepartmentComboBox.SelectedIndex = -1
TitleComboBox.Text = String.Empty
DepartmentComboBox.Text = String.Empty

'Unselect the currently selected faculty member in the


Listbox
EmployeeListBox.SelectedIndex = -1

'Reset focus to the employee name text box


EmployeeNameTextBox.Focus()
End Sub

Private Sub DisplaySelectedToolStripMenuItem_Click(ByVal


sender As System.Object, ByVal e As System.EventArgs) Handles
DisplaySelectedToolStripMenuItem.Click
'Use messagebox to display selected employee
If EmployeeListBox.SelectedIndex = -1 Then
MessageBox.Show("You must select an employee member
to display.", "No Selection Error", MessageBoxButtons.OK,
MessageBoxIcon.Error)
Else

MessageBox.Show(EmployeeListBox.SelectedItem.ToString, "Current
selection", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End Sub

Private Sub CountDepartmentsToolStripMenuItem_Click(ByVal


sender As System.Object, ByVal e As System.EventArgs) Handles
CountDepartmentsToolStripMenuItem.Click
'Display a message box with the count of the number of
departments
Dim MessageString As String = "Number of departments: " &
DepartmentComboBox.Items.Count.ToString()
Dim TitleString As String = "Count of Departments"
MessageBox.Show(MessageString, TitleString,
MessageBoxButtons.OK, MessageBoxIcon.Information)
End Sub

Private Sub RemoveDepartmentToolStripMenuItem_Click(ByVal


sender As System.Object, ByVal e As System.EventArgs) Handles
RemoveDepartmentToolStripMenuItem.Click
'Declare dialog result variable
Dim ResponseDialogResult As DialogResult =
MessageBox.Show("Remove the selected department?", "Remove ?",
MessageBoxButtons.YesNo, MessageBoxIcon.Question,
MessageBoxDefaultButton.Button2)
If ResponseDialogResult = Windows.Forms.DialogResult.Yes
Then
'Remove the selected department from the listing

DepartmentComboBox.Items.Remove(DepartmentComboBox.SelectedItem)
'This next line of code clears the Text
'property of the ComboBox – this is automatic
'for the Remove method, but not for the last
'item in a list.
DepartmentComboBox.Text = String.Empty
End If
End Sub
Private Sub RemoveAtDepartmentToolStripMenuItem_Click(ByVal
sender As System.Object, ByVal e As System.EventArgs) Handles
RemoveAtDepartmentToolStripMenuItem.Click
'Try to remove the department if one is selected
Try
'Declare dialog result variable
Dim ResponseDialogResult As DialogResult =
MessageBox.Show("Remove the selected department?", "Remove ?",
MessageBoxButtons.YesNo, MessageBoxIcon.Question,
MessageBoxDefaultButton.Button2)
If ResponseDialogResult =
Windows.Forms.DialogResult.Yes Then
'Remove the selected department from the listing

DepartmentComboBox.Items.RemoveAt(DepartmentComboBox.SelectedInde
x)
'This next line of code clears the Text
'property of the ComboBox – this is automatic
'for the Remove method, but not for the last
'item in a list.
DepartmentComboBox.Text = String.Empty
End If
Catch ex As ArgumentOutOfRangeException
MessageBox.Show("You must select a department to
remove.", "No Selection Was Made", MessageBoxButtons.OK,
MessageBoxIcon.Error)
End Try
End Sub

Private Sub CountToolStripMenuItem_Click(ByVal sender As


System.Object, ByVal e As System.EventArgs) Handles
CountToolStripMenuItem.Click
'Demonstrates using nested For...Next loops.
Dim TotalLong As Long
Dim OuterIndexInteger As Integer
Dim InnerIndexInteger As Integer

'Start of the outer loop


For OuterIndexInteger = 1 To 3
'Start of the inner loop – each time we get here the
'inner loop starts all over again
For InnerIndexInteger = 1 To 6
TotalLong += 1
CountListBox.Items.Add(TotalLong.ToString)
Next InnerIndexInteger
'Exited inner loop – control transfers to outer loop
Next OuterIndexInteger
MessageBox.Show("Finished Counting.")
End Sub

Private Sub FruitTextBox_TextChanged(ByVal sender As


System.Object, ByVal e As System.EventArgs) Handles
FruitTextBox.TextChanged
'Initialize variables to control the search
Dim IndexInteger As Integer = 0
Dim FoundBoolean As Boolean = False
Dim ListItemString As String

'Start the search


Do While Not FoundBoolean And IndexInteger <
FruitListBox.Items.Count
'Compare the value in the TextBox to the ListBox
Items
ListItemString =
FruitListBox.Items(IndexInteger).ToString.ToUpper
If
ListItemString.StartsWith(FruitTextBox.Text.ToUpper) Then
'found a fruit name that starts with the Text
typed thus far
FruitListBox.SelectedIndex = IndexInteger
FoundBoolean = True
Else
IndexInteger += 1
End If
Loop

If FoundBoolean = False Then


MessageBox.Show("That fruit is not in the list.",
"Not Found", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End If
End Sub

Private Sub HelpToolStripMenuItem_Click(ByVal sender As


System.Object, ByVal e As System.EventArgs) Handles
HelpToolStripMenuItem.Click
MessageBox.Show("Programmed by D. Bock", "About Me",
MessageBoxButtons.OK, MessageBoxIcon.Information)
End Sub

Private Sub AboutToolStripMenuItem_Click(ByVal sender As


System.Object, ByVal e As System.EventArgs) Handles
AboutToolStripMenuItem.Click
'Display about message
Dim MessageString As String = "Programmed by D. Bock" &
ControlChars.NewLine & "Today's date and time: " & Date.Now
Dim TitleString As String = "About Ch07 VB University"
MessageBox.Show(MessageString, TitleString,
MessageBoxButtons.OK, MessageBoxIcon.Information)
End Sub

Private Function ValidData() As Boolean


'Assume data is not valid
ValidData = False
Dim MessageString, TitleString As String

If EmployeeNameTextBox.Text.Trim = String.Empty Then


'Business rule #1 - Name cannot be missing
MessageString = "Employee name is missing."
TitleString = "Employee name error"
MessageBox.Show(MessageString, TitleString,
MessageBoxButtons.OK, MessageBoxIcon.Error)
EmployeeNameTextBox.Focus()
EmployeeNameTextBox.SelectAll()

ElseIf TitleComboBox.SelectedIndex = -1 Then


'Business rule #2 - Title must be selected
'from the list provided in the ComboBox
MessageString = "Title was not selected."
TitleString = "Title error"
MessageBox.Show(MessageString, TitleString,
MessageBoxButtons.OK, MessageBoxIcon.Error)
TitleComboBox.Focus()

ElseIf DepartmentComboBox.Text.Trim = String.Empty Then


'Business rule #3 - Department must be selected
'or typed into the Text property of the ComboBox
MessageString = "Department name was not selected or
entered."
TitleString = "Department Name error"
MessageBox.Show(MessageString, TitleString,
MessageBoxButtons.OK, MessageBoxIcon.Error)
DepartmentComboBox.Focus()

ElseIf IsNumeric(SalaryTextBox.Text) = False OrElse


Decimal.Parse(SalaryTextBox.Text,
Globalization.NumberStyles.Currency) <= 0D Then
'Business rule #4 - Salary must be valid number > 0
MessageString = "Salary is missing or invalid-must be
greater than zero."
TitleString = "Salary error"
MessageBox.Show(MessageString, TitleString,
MessageBoxButtons.OK, MessageBoxIcon.Error)
SalaryTextBox.Focus()
SalaryTextBox.SelectAll()

Else
'Data passes all business rules
ValidData = True
End If
End Function

Private Sub ComputeInterestToolStripMenuItem_Click(ByVal


sender As System.Object, ByVal e As System.EventArgs) Handles
ComputeInterestToolStripMenuItem.Click
'Example For..Next loop that calculates compound
'interest on an investment
Dim InvestmentAmountDecimal As Decimal = 1000D '$1000
Dim TermInteger As Integer = 5 '5 years
Dim InterestSingle As Single = 1.0F 'Beginning for 1st
compound
Dim InterestRateSingle As Single = 0.06F '6% interest
rate

'Compute total effective interest rate in loop


For Index = 1 To TermInteger
InterestSingle = InterestSingle * (1.0F +
InterestRateSingle)
Next Index

'Calculate total investment at the end of


'5 years including compound interest
Dim EndingValueDecimal = InvestmentAmountDecimal *
InterestSingle

MessageBox.Show("Ending balance: " &


EndingValueDecimal.ToString("C2"), "Your Balance",
MessageBoxButtons.OK, MessageBoxIcon.Information)
End Sub
'Project: Ch08VBUniversity-Version1
'D. Bock
'Today's Date

Option Strict On

Public Class BookStore1

'Declare a Product structre


Structure Product
Dim ProductIDString As String
Dim DescriptionString As String
Dim QuantityInteger As Integer
Dim PriceDecimal As Decimal
End Structure

'Module-level declarations
Private NumberProductsInteger As Integer = 7 'number of products
'Array of type Product
Private InventoryProduct(NumberProductsInteger) As Product
Private TotalDueDecimal As Decimal 'total amount for individual customer

Private Sub BookStore1_Load(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles MyBase.Load
InventoryProduct(0).ProductIDString = "A402"
InventoryProduct(0).DescriptionString = "History of America Textbook"
InventoryProduct(0).QuantityInteger = 10
InventoryProduct(0).PriceDecimal = 65.55D

InventoryProduct(1).ProductIDString = "A804"
InventoryProduct(1).DescriptionString = "College Logo Tshirt"
InventoryProduct(1).QuantityInteger = 15
InventoryProduct(1).PriceDecimal = 18.99D

InventoryProduct(2).ProductIDString = "C344"
InventoryProduct(2).DescriptionString = "College Logo Sweat Pants"
InventoryProduct(2).QuantityInteger = 25
InventoryProduct(2).PriceDecimal = 25.99D

InventoryProduct(3).ProductIDString = "F554"
InventoryProduct(3).DescriptionString = "Drinking Mug"
InventoryProduct(3).QuantityInteger = 8
InventoryProduct(3).PriceDecimal = 5.49D

InventoryProduct(4).ProductIDString = "G302"
InventoryProduct(4).DescriptionString = "Pencil and Pen Set"
InventoryProduct(4).QuantityInteger = 15
InventoryProduct(4).PriceDecimal = 35.5D

InventoryProduct(5).ProductIDString = "M302"
InventoryProduct(5).DescriptionString = "College Logo Sweat Shirt"
InventoryProduct(5).QuantityInteger = 25
InventoryProduct(5).PriceDecimal = 22.99D

InventoryProduct(6).ProductIDString = "S499"
InventoryProduct(6).DescriptionString = "Intro to Philosophy Textbook"
InventoryProduct(6).QuantityInteger = 50
InventoryProduct(6).PriceDecimal = 85D

InventoryProduct(7).ProductIDString = "X599"
InventoryProduct(7).DescriptionString = "Intro to CMIS Textbook"
InventoryProduct(7).QuantityInteger = 75
InventoryProduct(7).PriceDecimal = 79.4D
End Sub

Private Sub SearchButton_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles SearchButton.Click
'Search the ProductIDString property of the inventoryProduct
'array to see if the value of ProductIDTextBox matches an ID
'in the array

'Start variables to control the search


Dim FoundBoolean As Boolean = False 'Control how long to search
Dim RowInteger As Integer = 0 'Current row in the search

'Loop to do the search


Do Until FoundBoolean = True Or RowInteger > NumberProductsInteger
'Compare textBox to array
If ProductIDTextBox.Text =
InventoryProduct(RowInteger).ProductIDString Then
'found a match - display other data to the readonly textboxes
DescriptionTextBox.Text =
InventoryProduct(RowInteger).DescriptionString
QuantityTextBox.Text =
InventoryProduct(RowInteger).QuantityInteger.ToString
PriceTextBox.Text =
InventoryProduct(RowInteger).PriceDecimal.ToString("C2")

'change variable to indicate we have a match


FoundBoolean = True
Else
'no match yet
RowInteger += 1
End If
Loop

'After the search determine if the ProductID was found


If FoundBoolean = False Then 'no match was found
'Clear the textbox controls that display product information
'except for the ProductID textbox
DescriptionTextBox.Clear()
QuantityTextBox.Clear()
PriceTextBox.Clear()

'Display message that the ProductID is not valid


MessageBox.Show("Reenter a valid product ID.", "Invalid
Identifier", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
ProductIDTextBox.Focus()
ProductIDTextBox.SelectAll()
End If
End Sub

Private Sub PurchaseToolStripMenuItem_Click(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles PurchaseToolStripMenuItem.Click
'Test to determine if a product was found.
If DescriptionTextBox.Text = String.Empty Then
'Cannot purchase, product was not found
MessageBox.Show("You must select a valid product before
purchasing.", "Cannot Purchase", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation)
ProductIDTextBox.Focus()
ProductIDTextBox.SelectAll()
Else
'Can purchase the product
'Build a string to display in the listbox control
Dim ProductString As String = ProductIDTextBox.Text & " - " &
DescriptionTextBox.Text & " - " & PriceTextBox.Text
PurchaseListBox.Items.Add(ProductString)

'Accumulate the total value of this customer order


'and display it to the output textbox
TotalDueDecimal += Decimal.Parse(PriceTextBox.Text,
Globalization.NumberStyles.Currency)
TotalDueTextBox.Text = TotalDueDecimal.ToString("C2")

'Here you can clear the form of product info if you think
'that is a good way to do the processing
ProductIDTextBox.Clear()
DescriptionTextBox.Clear()
PriceTextBox.Clear()
QuantityTextBox.Clear()
ProductIDTextBox.Focus()
End If
End Sub

Private Sub ResetToolStripMenuItem_Click(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles ResetToolStripMenuItem.Click
'Clear all text box controls
ProductIDTextBox.Clear()
DescriptionTextBox.Clear()
PriceTextBox.Clear()
QuantityTextBox.Clear()
TotalDueTextBox.Clear()

'Clear the list box control


PurchaseListBox.Items.Clear()

'Reset the total due module-level variable to zero


TotalDueDecimal = 0

'Set the focus to the product ID text box


ProductIDTextBox.Focus()
End Sub

Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
'Exit the form without asking to close
Me.Close()
End Sub

Private Sub SearchToolStripMenuItem_Click(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles SearchToolStripMenuItem.Click
'Call the Click event for the Search button control
SearchButton.PerformClick()
End Sub

Private Sub AboutToolStripMenuItem_Click(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles AboutToolStripMenuItem.Click
Dim MessageString As String = "Version 1 of the Book Store Project" &
ControlChars.NewLine & "Today's date/time: " & Date.Now
Dim TitleString As String = "About Version 1"
MessageBox.Show(MessageString, TitleString, MessageBoxButtons.OK,
MessageBoxIcon.Information)
End Sub

End Class

This solution shows the Ch08VBUniversity-Version2 exercise code of the


Bookstore2.vb form.
'Project: Ch08VBUniversity - Start Project
'D. Bock
'Today's Date

Option Strict On

Public Class BookStore2

'Module level declarations


Structure Product
Dim ProductIDString As String
Dim DescriptionString As String
Dim QuantityInteger As Integer
Dim PriceDecimal As Decimal
End Structure

Private NumberProductsInteger As Integer = 7


Private InventoryProduct(NumberProductsInteger) As Product
Private TotalDueDecimal As Decimal 'total due for a customer
'Array to store the total sales for each product
Private ProductSalesTotalDecimal(NumberProductsInteger) As Decimal

Private Sub BookStore1_Load(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles MyBase.Load
'Initialize values - InventoryProduct array
InventoryProduct(0).ProductIDString = "A402"
InventoryProduct(0).DescriptionString = "History of America Textbook"
InventoryProduct(0).QuantityInteger = 10
InventoryProduct(0).PriceDecimal = 65.55D

InventoryProduct(1).ProductIDString = "A804"
InventoryProduct(1).DescriptionString = "College Logo Tshirt"
InventoryProduct(1).QuantityInteger = 15
InventoryProduct(1).PriceDecimal = 18.99D

InventoryProduct(2).ProductIDString = "C344"
InventoryProduct(2).DescriptionString = "College Logo Sweat Pants"
InventoryProduct(2).QuantityInteger = 25
InventoryProduct(2).PriceDecimal = 25.99D

InventoryProduct(3).ProductIDString = "F554"
InventoryProduct(3).DescriptionString = "Drinking Mug"
InventoryProduct(3).QuantityInteger = 8
InventoryProduct(3).PriceDecimal = 5.49D
InventoryProduct(4).ProductIDString = "G302"
InventoryProduct(4).DescriptionString = "Pencil and Pen Set"
InventoryProduct(4).QuantityInteger = 15
InventoryProduct(4).PriceDecimal = 35.5D

InventoryProduct(5).ProductIDString = "M302"
InventoryProduct(5).DescriptionString = "College Logo Sweat Shirt"
InventoryProduct(5).QuantityInteger = 25
InventoryProduct(5).PriceDecimal = 22.99D

InventoryProduct(6).ProductIDString = "S499"
InventoryProduct(6).DescriptionString = "Intro to Philosophy Textbook"
InventoryProduct(6).QuantityInteger = 50
InventoryProduct(6).PriceDecimal = 85D

InventoryProduct(7).ProductIDString = "X599"
InventoryProduct(7).DescriptionString = "Intro to CMIS Textbook"
InventoryProduct(7).QuantityInteger = 75
InventoryProduct(7).PriceDecimal = 79.4D
End Sub

Private Sub SearchButton_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles SearchButton.Click
'Search the ProductIDString property of the inventoryProduct
'array to see if the value of ProductIDTextBox matches an ID
'in the array

'Start variables to control the search


Dim FoundBoolean As Boolean = False 'Control how long to search
Dim RowInteger As Integer = 0 'Current row in the search

'Loop to do the search


Do Until FoundBoolean = True Or RowInteger > NumberProductsInteger
'Compare textBox to array
If ProductIDTextBox.Text =
InventoryProduct(RowInteger).ProductIDString Then
'found a match - display other data to the readonly textboxes
ProductIDComboBox.SelectedItem = ProductIDTextBox.Text
DescriptionTextBox.Text =
InventoryProduct(RowInteger).DescriptionString
QuantityTextBox.Text =
InventoryProduct(RowInteger).QuantityInteger.ToString
PriceTextBox.Text =
InventoryProduct(RowInteger).PriceDecimal.ToString("C2")

'change variable to indicate we have a match


FoundBoolean = True
Else
'no match yet
RowInteger += 1
End If
Loop

'After the search determine if the ProductID was found


If FoundBoolean = False Then 'no match was found
'Clear the textbox controls that display product information
'except for the ProductID textbox
DescriptionTextBox.Clear()
QuantityTextBox.Clear()
PriceTextBox.Clear()
ProductIDComboBox.SelectedIndex = -1

'Display message that the ProductID is not valid


MessageBox.Show("Reenter a valid product ID.", "Invalid
Identifier", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
ProductIDTextBox.Focus()
ProductIDTextBox.SelectAll()
End If
End Sub

Private Sub PurchaseToolStripMenuItem_Click(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles PurchaseToolStripMenuItem.Click
'Test to determine if a product was found.
If DescriptionTextBox.Text = String.Empty Then
'Cannot purchase, product was not found
MessageBox.Show("You must select a valid product before
purchasing.", "Cannot Purchase", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation)
ProductIDTextBox.Focus()
ProductIDTextBox.SelectAll()
Else
'Can purchase the product
'Build a string to display in the listbox control
Dim ProductString As String = ProductIDTextBox.Text & " - " &
DescriptionTextBox.Text & " - " & PriceTextBox.Text
PurchaseListBox.Items.Add(ProductString)

'Accumulate the total value of this customer order


'and display it to the output textbox
TotalDueDecimal += Decimal.Parse(PriceTextBox.Text,
Globalization.NumberStyles.Currency)
TotalDueTextBox.Text = TotalDueDecimal.ToString("C2")

'Accumulate total sales by product to an array


Dim IndexInteger As Integer = ProductIDComboBox.SelectedIndex
ProductSalesTotalDecimal(IndexInteger) +=
Decimal.Parse(PriceTextBox.Text, Globalization.NumberStyles.Currency)

'Here you can clear the form of product info if you think
'that is a good way to do the processing
ProductIDComboBox.SelectedIndex = -1
ProductIDTextBox.Clear()
DescriptionTextBox.Clear()
PriceTextBox.Clear()
QuantityTextBox.Clear()
ProductIDTextBox.Focus()
End If
End Sub

Private Sub ResetToolStripMenuItem_Click(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles ResetToolStripMenuItem.Click
'Clear all text box and combobox controls
ProductIDComboBox.SelectedIndex = -1
ProductIDTextBox.Clear()
DescriptionTextBox.Clear()
PriceTextBox.Clear()
QuantityTextBox.Clear()
TotalDueTextBox.Clear()

'Clear the list box control


PurchaseListBox.Items.Clear()

'Reset the total due module-level variable to zero


TotalDueDecimal = 0

'Set the focus to the product ID text box


ProductIDTextBox.Focus()
End Sub

Private Sub SearchToolStripMenuItem_Click(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles SearchToolStripMenuItem.Click
'Call the Click event for the Search button control
SearchButton.PerformClick()
End Sub

Private Sub AboutToolStripMenuItem_Click(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles AboutToolStripMenuItem.Click
Dim MessageString As String = "Version 2 of the Book Store Project" &
ControlChars.NewLine & "Today's date/time: " & Date.Now
Dim TitleString As String = "About Version 2"
MessageBox.Show(MessageString, TitleString, MessageBoxButtons.OK,
MessageBoxIcon.Information)
End Sub

Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
'Close the form
Me.Close()
End Sub

Private Sub ProductIDComboBox_SelectedIndexChanged(ByVal sender As


System.Object, ByVal e As System.EventArgs) Handles
ProductIDComboBox.SelectedIndexChanged
'Test to determine if a product has been selected
If ProductIDComboBox.SelectedIndex <> -1 Then
'Store the selectedIndex to variable
Dim RowInteger As Integer = ProductIDComboBox.SelectedIndex

'Based on RowInteger, display values to TextBox controls


'from the array named inventoryProduct
ProductIDTextBox.Text =
InventoryProduct(RowInteger).ProductIDString
DescriptionTextBox.Text =
InventoryProduct(RowInteger).DescriptionString
QuantityTextBox.Text =
InventoryProduct(RowInteger).QuantityInteger.ToString("N0")
PriceTextBox.Text =
InventoryProduct(RowInteger).PriceDecimal.ToString("C2")
End If
End Sub
Private Sub TotalSalesByProductToolStripMenuItem_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
TotalSalesByProductToolStripMenuItem.Click
'Display output to immediate window
Dim RowInteger As Integer
Dim SalesString As String = "ProductID" & vbTab & "Dollar Sales" &
vbCrLf
For Each ProductItem As Product In InventoryProduct
'Build string to display
SalesString &= ProductItem.ProductIDString & vbTab & vbTab &
ProductSalesTotalDecimal(RowInteger).ToString("C2") & vbCrLf

'Increment RowInteger
RowInteger += 1
Next

'Display string to a MessageBox


'Debug.WriteLine(SalesString)
MessageBox.Show(SalesString, "Sales for all Products",
MessageBoxButtons.OK, MessageBoxIcon.Information)
End Sub

End Class

This solution shows the Ch08VBUniversity-Version3 exercise code for the


Bookstore3.vb form.
'Project: Ch08VBUniversity-Version3
'D. Bock
'Today's Date

Option Strict On

Public Class BookStore3

'Module-level declarations
Private NumberProductsInteger As Integer = 7 'number of products
Private TotalDueDecimal As Decimal 'total amount for individual customer

'Array to store the total sales for each product


Private ProductSalesTotalDecimal(NumberProductsInteger) As Decimal

'Module-level variable to store row and column values


Private RowInteger, ColumnInteger As Integer

'Declare two-dimensional inventory array


Private InventoryString(,) As String = { _
{"A402", "History of America Textbook", "2", "$65.55"}, _
{"A804", "College Logo Tshirt", "15", "$18.99"}, _
{"C344", "College Logo Sweat Pants", "25", "$25.99"}, _
{"F554", "Drinking Mug", "8", "$5.49"}, _
{"G302", "Pencil and Pen Set", "15", "$35.50"}, _
{"M302", "College Logo Sweat Shirt", "25", "$22.99"}, _
{"S499", "Intro to Philosophy Textbook", "50", "$85.00"}, _
{"X599", "Intro to CMIS Textbook", "75", "$79.40"}}

Private Sub SearchButton_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles SearchButton.Click, SearchToolStripMenuItem.Click
'Search the ProductIDString property of the InventoryString
'array to see if the value of ProductIDTextBox matches an ID
'in the array

'Start variables to control the search


Dim FoundBoolean As Boolean = False 'Control how long to search
RowInteger = 0 'Current row in the search
ColumnInteger = 0 'Search column zero

'Loop to do the search


Do Until FoundBoolean = True Or RowInteger > NumberProductsInteger
'Compare TextBox to array
If ProductIDTextBox.Text = InventoryString(RowInteger,
ColumnInteger) Then
'found a match - display data to the readonly TextBoxes
DescriptionTextBox.Text = InventoryString(RowInteger, 1)
QuantityTextBox.Text = InventoryString(RowInteger, 2)
PriceTextBox.Text = InventoryString(RowInteger, 3)

'change variable to indicate we have a match


FoundBoolean = True
Else
'no match yet
RowInteger += 1
End If
Loop

'After the search determine if the ProductID was found


If FoundBoolean = False Then 'no match was found
'Clear the textbox controls that display product information
'except for the ProductIDTextBox
DescriptionTextBox.Clear()
QuantityTextBox.Clear()
PriceTextBox.Clear()

'Display message that the ProductID is not valid


MessageBox.Show("Reenter a valid product ID.", "Invalid
Identifier", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
ProductIDTextBox.Focus()
ProductIDTextBox.SelectAll()
Else
If Convert.ToInt32(QuantityTextBox.Text) = 0 Then
PurchaseToolStripMenuItem.Enabled = False
Else
PurchaseToolStripMenuItem.Enabled = True
End If
End If
End Sub

Private Sub PurchaseToolStripMenuItem_Click(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles PurchaseToolStripMenuItem.Click
'Test to determine if a product was found.
If DescriptionTextBox.Text = String.Empty Then
'Cannot purchase, product was not found
MessageBox.Show("You must select a valid product before
purchasing.", "Cannot Purchase", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation)
ProductIDTextBox.Focus()
ProductIDTextBox.SelectAll()
Else
If Convert.ToInt32(Me.InventoryString(RowInteger, 2)) > 0I Then
'Subtract 1 from quantity
Dim QuantityInteger As Integer =
Convert.ToInt32(Me.InventoryString(RowInteger, 2)) - 1I
'Store the quantity back to the array
InventoryString(RowInteger, 2) = QuantityInteger.ToString

'Can purchase the product


'Build a string to display in the ListBox control
Dim ProductString As String = ProductIDTextBox.Text & " - " &
DescriptionTextBox.Text & " - " & PriceTextBox.Text
PurchaseListBox.Items.Add(ProductString)

'Accumulate the total value of this customer order


'and display it to the output TextBox
TotalDueDecimal += Decimal.Parse(PriceTextBox.Text,
Globalization.NumberStyles.Currency)
TotalDueTextBox.Text = TotalDueDecimal.ToString("C2")

'Accumulate total sales by product


ProductSalesTotalDecimal(RowInteger) +=
Decimal.Parse(PriceTextBox.Text, Globalization.NumberStyles.Currency)

'Here you can clear the form of product info if you think
'that is a good way to do the processing
ProductIDTextBox.Clear()
DescriptionTextBox.Clear()
PriceTextBox.Clear()
QuantityTextBox.Clear()
ProductIDTextBox.Focus()
Else
MessageBox.Show("Ask for a raincheck, we are out of that
product.", "Out of Stock", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End If
End If
End Sub

Private Sub ResetToolStripMenuItem_Click(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles ResetToolStripMenuItem.Click
'Clear all TextBox control
ProductIDTextBox.Clear()
DescriptionTextBox.Clear()
PriceTextBox.Clear()
QuantityTextBox.Clear()
TotalDueTextBox.Clear()

'Clear the ListBox control


PurchaseListBox.Items.Clear()

'Reset the total due module-level variable to zero


TotalDueDecimal = 0

'Set the focus to the ProductIDTextBox


ProductIDTextBox.Focus()
End Sub

Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
'Exit the form without asking to close
Me.Close()
End Sub

Private Sub AboutToolStripMenuItem_Click(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles AboutToolStripMenuItem.Click
Dim MessageString As String = "Version 3 of the Book Store Project" &
ControlChars.NewLine & "Today's date/time: " & Date.Now
Dim TitleString As String = "About Version 3"
MessageBox.Show(MessageString, TitleString, MessageBoxButtons.OK,
MessageBoxIcon.Information)
End Sub

Private Sub TotalSalesByProductToolStripMenuItem_Click(ByVal sender As


System.Object, ByVal e As System.EventArgs) Handles
TotalSalesByProductToolStripMenuItem.Click
'Display output to a MessageBox
Dim RowInteger As Integer
Dim SalesString As String = "ProductID" & vbTab & "Dollar Sales" &
vbCrLf
For RowInteger = 0 To NumberProductsInteger
'Build string to display
SalesString &= InventoryString(RowInteger, 0) & vbTab & vbTab &
ProductSalesTotalDecimal(RowInteger).ToString("C") & vbCrLf
Next

'Display string to a MessageBox


'Debug.WriteLine(SalesString)
MessageBox.Show(SalesString, "Sales for all Products",
MessageBoxButtons.OK, MessageBoxIcon.Information)
End Sub

End class

Student Details Form

'Ch10VBUniverrsity - StudentDetails Form

'D. Bock

'Today's Date

Option Strict On
Public Class StudentDetails

Private Sub StudentBindingNavigatorSaveItem_Click(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles StudentBindingNavigatorSaveItem.Click

'Trap any exceptions during student table update

Try

If ValidData() Then

'Me.Validate()

Me.StudentBindingSource.EndEdit()

Me.TableAdapterManager.UpdateAll(Me.StudentDetailsDataSet)

'Call sub procedure to enable BindingNavigator controls

'by sending a parameter value True

Me.SetControls(True)

End If

Catch ex As Exception

Dim MessageString As String = "Report this error to the system administrator:


" & ControlChars.NewLine & ex.Message

Dim TitleString As String = "Error During Save Operation"

MessageBox.Show(MessageString, TitleString, MessageBoxButtons.OK,


MessageBoxIcon.Error)

End Try

End Sub

Private Sub StudentDetails_Load(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles MyBase.Load

'Trap exceptions that occur during data load

Try

Me.StatesTableAdapter.Fill(Me.StatesDataSet.States)
Me.StudentTableAdapter.Fill(Me.StudentDetailsDataSet.Student)

Catch ex As Exception

Dim MessageString As String = "Report this error to the system administrator:


" & ControlChars.NewLine & ex.Message

Dim TitleString As String = "Student Details Data Load Failed"

MessageBox.Show(MessageString, TitleString, MessageBoxButtons.OK,


MessageBoxIcon.Error)

End Try

End Sub

Private Sub SetControls(ByVal ValueBoolean As Boolean)

'This sub procedure sets the user interface for the

'BindingNavigator control and bound controls for Edit/Add

'operations

'ReadOnly/Not ReadOnly the bound controls

SSNMaskedTextBox.ReadOnly = ValueBoolean

LastNameTextBox.ReadOnly = ValueBoolean

FirstNameTextBox.ReadOnly = ValueBoolean

MiddleInitialTextBox.ReadOnly = ValueBoolean

AddressTextBox.ReadOnly = ValueBoolean

CityTextBox.ReadOnly = ValueBoolean

ZipMaskedTextBox.ReadOnly = ValueBoolean

PhoneMaskedTextBox.ReadOnly = ValueBoolean

EmailAddressTextBox.ReadOnly = ValueBoolean

MajorTextBox.ReadOnly = ValueBoolean

AccountBalanceTextBox.ReadOnly = ValueBoolean

'Remark out next line when StateComboBox replaces


'the StateCodeTextBox and add the line of

'code to enable the StateComboBox

'StateCodeTextBox.ReadOnly = ValueBoolean

StateComboBox.Enabled = Not ValueBoolean

'Make the Move, Position, and Buttons

'(except Save and Cancel) Invisible

BindingNavigatorMoveFirstItem.Visible = ValueBoolean

BindingNavigatorMoveLastItem.Visible = ValueBoolean

BindingNavigatorMoveNextItem.Visible = ValueBoolean

BindingNavigatorMovePreviousItem.Visible = ValueBoolean

BindingNavigatorPositionItem.Visible = ValueBoolean

BindingNavigatorCountItem.Visible = ValueBoolean

BindingNavigatorAddNewItem.Visible = ValueBoolean

BindingNavigatorDeleteItem.Visible = ValueBoolean

EditToolStripButton.Visible = ValueBoolean

'Enable/disable the Save and Cancel Buttons

StudentBindingNavigatorSaveItem.Enabled = Not ValueBoolean

CancelToolStripButton.Enabled = Not ValueBoolean

'Enable/disable ComboBox

LastNameComboBox.Enabled = ValueBoolean

End Sub

Private Sub EditToolStripButton_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles EditToolStripButton.Click

'Call SetControls with False to alter the form to

'allow editing a data row


SetControls(False)

End Sub

Private Sub CancelToolStripButton_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles CancelToolStripButton.Click

'Cancel the operation

StudentBindingSource.CancelEdit()

'Call SetControls with True to alter the form to

'make the form ReadOnly

SetControls(True)

End Sub

Private Sub BindingNavigatorAddNewItem_Click(ByVal sender As System.Object, ByVal e


As System.EventArgs) Handles BindingNavigatorAddNewItem.Click

'Call SetControls with False to alter the form to

'allow adding a data row

SetControls(False)

'Set focus

SSNMaskedTextBox.Focus()

End Sub

Private Sub BindingNavigatorDeleteItem_Click(ByVal sender As System.Object, ByVal e


As System.EventArgs) Handles BindingNavigatorDeleteItem.Click

'Delete the row if there is no relationship to

'existing data rows in the ENROLLMENT table

'Store the current DataSet position in case the deletion fails

Dim RowNumberInteger As Integer = StudentBindingSource.Position


Try

Dim ResponseDialogResult As DialogResult = MessageBox.Show("Confirm to delete


the student record.", "Delete Y/N?", MessageBoxButtons.YesNo, MessageBoxIcon.Question,
MessageBoxDefaultButton.Button2)

If ResponseDialogResult = Windows.Forms.DialogResult.Yes Then

'Delete the row by removing the current record,

'ending the edit, and calling the Update method

StudentBindingSource.RemoveCurrent()

StudentBindingSource.EndEdit()

TableAdapterManager.UpdateAll(StudentDetailsDataSet)

End If

Catch exOleDb As OleDb.OleDbException

'The deletion attempt failed due to a relationship

'to existing data rows in the ENROLLMENT table

'Restore the deleted row with the RejectChanges method

StudentDetailsDataSet.RejectChanges()

'Reposition to the row that was deleted

StudentBindingSource.Position = RowNumberInteger

'Display appropriate error message

MessageBox.Show("This student cannot be deleted - the student is enrolled in


courses." & ControlChars.NewLine & exOleDb.Message, "Delete Operation Error",
MessageBoxButtons.OK, MessageBoxIcon.Error)

Catch ex As Exception
'Some other exception was triggered

MessageBox.Show("Unexpected error in delete operation: " &


ControlChars.NewLine & ex.Message, "Delete Operation Error", MessageBoxButtons.OK,
MessageBoxIcon.Error)

End Try

End Sub

Private Function ValidData() As Boolean

'Initialize function return value

ValidData = False

Dim MessageString As String

'Test SSN is correct length

'Test existence of values in each textbox

If SSNMaskedTextBox.MaskCompleted = False Then

'The SSN value is not completes

MessageString = "SSN value is not complete."

MessageBox.Show(MessageString, "Data Error", MessageBoxButtons.OK,


MessageBoxIcon.Error)

SSNMaskedTextBox.Focus()

SSNMaskedTextBox.SelectAll()

ElseIf LastNameTextBox.Text.Trim = String.Empty Then

'Validate Last Name

MessageString = "Last name is required."

MessageBox.Show(MessageString, "Data Error", MessageBoxButtons.OK,


MessageBoxIcon.Error)

LastNameTextBox.Focus()

LastNameTextBox.SelectAll()

ElseIf FirstNameTextBox.Text.Trim = String.Empty Then

'Validate First Name


MessageString = "First name is required."

MessageBox.Show(MessageString, "Data Error", MessageBoxButtons.OK,


MessageBoxIcon.Error)

FirstNameTextBox.Focus()

FirstNameTextBox.SelectAll()

ElseIf AddressTextBox.Text.Trim = String.Empty Then

'Validate Address

MessageString = "Address is required."

MessageBox.Show(MessageString, "Data Error", MessageBoxButtons.OK,


MessageBoxIcon.Error)

AddressTextBox.Focus()

AddressTextBox.SelectAll()

ElseIf CityTextBox.Text.Trim = String.Empty Then

'Validate City

MessageString = "City is required."

MessageBox.Show(MessageString, "Data Error", MessageBoxButtons.OK,


MessageBoxIcon.Error)

CityTextBox.Focus()

CityTextBox.SelectAll()

ElseIf StateComboBox.SelectedIndex = -1 Then

'Validate State

MessageString = "State is required."

MessageBox.Show(MessageString, "Data Error", MessageBoxButtons.OK,


MessageBoxIcon.Error)

StateComboBox.Focus()

ElseIf ZipMaskedTextBox.MaskCompleted = False Then

'Zip code required

MessageString = "Zip code is incomplete."

MessageBox.Show(MessageString, "Data Error", MessageBoxButtons.OK,


MessageBoxIcon.Error)

ZipMaskedTextBox.Focus()
ZipMaskedTextBox.SelectAll()

ElseIf AccountBalanceTextBox.Text.Trim <> String.Empty AndAlso


IsNumeric(AccountBalanceTextBox.Text) = False Then

'Validate Account Balance is numeric if there is a value stored here

MessageString = "Account balance must be a numeric amount."

MessageBox.Show(MessageString, "Data Error", MessageBoxButtons.OK,


MessageBoxIcon.Error)

AccountBalanceTextBox.Focus()

AccountBalanceTextBox.SelectAll()

Else

'All of the data is valid

ValidData = True

End If

End Function

Private Sub AccountBalanceTextBox_KeyPress(ByVal sender As Object, ByVal e As


System.Windows.Forms.KeyPressEventArgs) Handles AccountBalanceTextBox.KeyPress

'Allow Backspace (8), numeric keys (48 to 57), comma (44),

'decimal point (46)and dollar sign (36)

Select Case Asc(e.KeyChar)

Case 8, 36, 44, 46, 48 To 57

e.Handled = False 'Allow the key

Case Else

e.Handled = True 'Ignore the key

End Select

End Sub

End Class

You might also like