System.InvalidCastException
エラーをキャッチしようとしています。私が電卓に数字を入力すると、プログラムは正常に実行されます。計算ボタンが何も押されずにテキストボックスに押された場合、私はキャストエラーConversion from string "" to type 'Decimal' is not valid.
を取得しますが、エラーが表示される理由を理解しています。私はそれについて何をすべきかわかりません。プログラムがnullデータをダンプし、ユーザーからの入力を待つことに戻ります。あなたはTextBox
からの入力を取得している場合のおかげ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