Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
833 views
in Technique[技术] by (71.8m points)

vb.net - "Conversion from string "" to type 'Double' is not valid." In VB

When I try to run the program to calculate payment and total intrest I get "Conversion from string "" to type 'Double' is not valid."

What am I doing wrong?

Dim P As Double
Dim R As Double
Dim N As Double
Dim Payment As Double
Dim totalInterest As Double

Private Sub btnAnalyze_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAnalyze.Click

P = CDbl(txtAmount.Text)
N = CDbl(txtDuration.Text)
R = CDbl(txtInterestRate.Text)

Payment = (P * R) / (1 - (1 + R) ^ (-N))
totalInterest = (N * Payment) - P

Payment = CDbl(txtPayment.Text)
totalInterest = CDbl(txtInterest.Text)

If P < 0 Then
MessageBox.Show("Please enter in loan amount")

End If

If R <= 0 Then
MessageBox.Show("Please enter in loan amount")

End If

If N <= 0 Then
MessageBox.Show("Please enter in loan amount")

End If


End Sub
End Class
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One of your TextBox items has not been filled in.

As such, when you use CDbl, such as P = CDbl(txtAmount.Text), if the TextBox is empty, it will cause this error.

A better option would be to use Double.TryParse instead of CDbl, as it will allow you to raise a proper message:

Private Sub btnAnalyze_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAnalyze.Click

If Not Double.TryParse(txtAmount.Text, P) Then
     MessageBox.Show("Please correct the loan amount")
     Exit Sub
End If

' Do the same for all other CDbl checks

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...