2011-09-12 8 views
1

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 

答えて

1

を行うことができ、ユーザがCDecも失敗した場合には、文字を入力することが可能です。

代わりにDecimal.TryParseを使用できます。

Dim decInHours As Decimal 
Dim decInWage As Decimal  
If Not Decimal.TryParse(txtInHours.Text, decInHours) Then 
     MessageBox.Show("Please enter a number in the hours box", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1) 
     Exit Sub ' As in answer from Fredou. 
End If 

If Not Decimal.TryParse(txtInWage.Text, decInWage) Then 
     MessageBox.Show("Please enter a number in the wage box", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1) 
     Exit Sub ' As in answer from Fredou. 
End If 
1

はあなたが

If txtInWage.Text = "" Then 
    MessageBox.Show("Please enter a number in the wage box", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1) 
    exit sub 
End If 
関連する問題