我一直试图阻止用户在文本框中输入字母。我尝试使用If语句在出现用户错误时显示一个消息框,但程序仍然崩溃。
崩溃的代码行是:
hours = CDec(txtHoursWorked.Text)
payPerHour = CDec(txtHourlyPay.Text)
我试过了:
小时= CDec(IsNumeric(txtHoursWorked.Text))
payPerHour = CDec(IsNumeric(txtHourlyPay.Text))
但这导致我的计算不正确
错误是:
发生了System.InvalidCastException
我的完整代码是:
Option Strict On
Option Explicit On
Public Class frmPay
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
Dim hours, payPerHour, overtimeHours, pay As Decimal
InputData(hours, payPerHour)
CalculateValues(hours, payPerHour, overtimeHours, pay)
DisplayData(overtimeHours, pay)
End Sub
Sub InputData(ByRef hours As Decimal, ByRef payPerHour As Decimal)
If IsNumeric(txtHoursWorked.Text) = False Then
MessageBox.Show("Please Enter A Value")
ElseIf IsNumeric(txtHourlyPay.Text) = False Then
MessageBox.Show("Please Enter A Value")
End If
If (txtHoursWorked.Text) = "" Then
MessageBox.Show("Please Enter A Value")
ElseIf (txtHourlyPay.Text) = "" Then
MessageBox.Show("Please Enter A Value")
End If
hours = CDec(txtHoursWorked.Text)
payPerHour = CDec(txtHourlyPay.Text)
End Sub
Sub CalculateValues(hours As Decimal, payPerHour As Double, ByRef overtimeHours As Decimal, ByRef pay As Decimal)
overtimeHours = Math.Abs(40 - hours)
If hours <= 40 Then
pay = CDec((payPerHour * hours))
ElseIf hours > 40 Then
pay = CDec((CDec(payPerHour * hours) + (payPerHour * 1.5) * (overtimeHours)))
End If
End Sub
Sub DisplayData(overtimeHours As Decimal, pay As Decimal)
txtOvertime.Text = CStr(overtimeHours)
txtWeeksPay.Text = pay.ToString("C")
End Sub
End Class
我的代码中缺少什么或做错了什么?