Visual Basic 2012“Microsoft.VisualBasic.dll中出现'System.InvalidCastException'类型的第一次机会异常”

时间:2014-10-07 16:55:14

标签: visual-studio-2012

Public Class Form1    
    Private Sub btn_calculate_Click(sender As Object, e As EventArgs) Handles btn_calculate.Click
        Dim MonthPayment As Double
        Dim LoanAmount As Double = txtbox_loan.Text
        Dim IntRate As Double = txtbox_IntRate.Text
        Dim Years As Double = txtbox_years.Text
        Dim tempI, temp1, temp2 As Double 'temporary variables'
        tempI = IntRate / 1200
        temp1 = (1 + tempI) ^ ((-12) * Years)
        temp2 = (tempI / (1 - temp1))
        MonthPayment = temp2 * LoanAmount
        txtbox_MonthPayment.Text = "$" & Math.Round(MonthPayment, 2)
    End Sub
End Class

这是我到目前为止所拥有的。我一直收到错误A first chance exception of type 'System.InvalidCastException' occurred in Microsoft.VisualBasic.dll,它突出显示LoanAmount As Double = txtbox_loan.Text,我想我需要改变它是一个字符串,但不知道如何。有什么建议吗?

1 个答案:

答案 0 :(得分:1)

通常,您不能将字符串分配给double变量。为了与旧的VB6代码兼容,Visual Studio提供了在项目属性中关闭此行为设置Option Strict Off的选项。

我强烈建议将Option Strict设置为On,因为当Option Strict Off启用自动转换处理时,这种类型的分配可能会非常危险。

回到您的代码,您需要使用double.TryParse并编写

Dim LoanAmount As Double
if Not double.TryParse(txtbox_loan.Text, LoanAmout) then
   .... Message for your user ....conversion not possible.. Not a valid double number ??? 
End If

等等,需要转换的其他数值