我正試圖抓住System.InvalidCastException
錯誤。如果我在計算器中輸入一個數字,程序運行正常。如果在文本框中沒有任何內容按下計算按鈕,我會得到投射錯誤Conversion from string "" to type 'Decimal' is not valid.
我明白爲什麼我會收到錯誤。我不知道該怎麼做。我想讓程序轉儲空數據並返回等待來自用戶的輸入。由於如何處理vb.net中的投射錯誤
Private Sub btnCalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalculate.Click
Dim FedTaxRate = 0.13 ' constants for taxes and work week
Dim StateTaxRate = 0.07
Dim StandWorkWeek = 40
Dim GrossPay As Decimal ' variables
Dim NetPay As Decimal
If txtInWage.Text = "" Then
MessageBox.Show("Please enter a number in the wage box", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1)
End If
If txtInHours.Text = "" Then
MessageBox.Show("Please enter a number in the hours box", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1)
End If
Dim decInHours = CDec(txtInHours.Text) 'converts text boxes to numerical data
Dim decInWage = CDec(txtInWage.Text)
If decInHours <= StandWorkWeek Then 'calculates gross and net pay as well as taxes. Also includes overtime after 40 hours
GrossPay = (decInHours * decInWage)
ElseIf decInHours > StandWorkWeek Then
GrossPay = (decInWage * StandWorkWeek) + (decInHours - StandWorkWeek) * (decInWage * 1.5)
End If
NetPay = GrossPay - (GrossPay * FedTaxRate) - (GrossPay * StateTaxRate)
lblGrossPay.Text = GrossPay.ToString("c")
lblNetPay.Text = NetPay.ToString("c")
lblFedTax.Text = (GrossPay * FedTaxRate).ToString("c")
lblStateTax.Text = (GrossPay * StateTaxRate).ToString("C")
End Sub