2011-09-12 18 views
1

我正試圖抓住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 

回答

1

如果你從一個TextBox獲得輸入,則有可能用戶可以輸入字母,在這種情況下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