从字符串“”到“Double”类型的转换不是有效的初学者类

时间:2013-04-10 04:43:58

标签: visual-studio-2012

当我尝试“清除”程序中的文本框时,我遇到了以下问题。这是一个初学者的课程,所以我应该能够用我迄今学到的东西来解决错误。每当我按下NextYear时,该程序基本上都是计算利率和资本增长。当我按下“清除”按钮时,它会显示错误并指出capital = CDbl(txtInitialCap.Text)事件下的txtRate_TextChanged语法。

Private year As Integer
Private capital As Double

Private Sub btnNextYear_Click(sender As Object, e As EventArgs) Handles btnNextYear.Click
    Dim interestAmount, interestRate As Double
    '
    ' Assign value to InterestRate variable from text property
    '
    interestRate = CDbl(txtRate.Text)
    '
    ' Calculate new values for year, interest amount and capital
    '
    year = year + 1
    interestAmount = capital * interestRate
    capital = capital + interestAmount
    '
    ' Assign the values to the textboxes
    '
    txtYear.Text = year
    txtInterest.Text = interestAmount
    txtCapital.Text = capital


Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
        txtInitialCap.Text = vbNullString
        txtRate.Text = vbNullString
        txtYear.Text = vbNullString
        txtInterest.Text = vbNullString
        txtCapital.Text = vbNullString
    End Sub

Private Sub txtInitialCap_LostFocus(sender As Object, e As EventArgs) Handles txtInitialCap.LostFocus
    '
    ' Reinitialise the capital variable since probably it was changed
    '
    capital = CDbl(txtInitialCap.Text)
End Sub

Private Sub txtInitialCap_TextChanged(sender As Object, e As EventArgs) Handles txtInitialCap.TextChanged
    '
    ' Reinitialise the year variable and the textboxes
    '
    year = 0
    txtYear.Text = vbNullString
    txtInterest.Text = vbNullString
    txtCapital.Text = vbNullString
End Sub

Private Sub txtRate_TextChanged(sender As Object, e As EventArgs) Handles txtRate.TextChanged
    year = 0
    capital = CDbl(txtInitialCap.Text)
    txtYear.Text = vbNullString
    txtInterest.Text = vbNullString
    txtCapital.Text = vbNullString
End Sub

1 个答案:

答案 0 :(得分:0)

我知道这是一篇旧帖子。如果其他人发现这个,我会回答。在txtRate_TextChanged中,您需要检查

txtInitialCap.Text != ""

如果文本为“”,则无法将其转换为double