你好我正在编写一个简单的VB表单,到目前为止一切都很好。但是,如果我为“SpaceLeftText.Text”留下一个空白输入框并点击回车,我会收到此错误:
“Microsoft.VisualBasic.dll中发生了'System.InvalidCastException'类型的未处理异常
其他信息:从字符串“”到“Double”类型的转换无效。
以下是我正在使用的代码:
Public Class Form1
Private Sub EnterButton_Click(sender As Object, e As EventArgs) Handles EnterButton.Click, MyBase.Activated
SpaceLeftText.Text = Math.Round((((Val(AxleLengthText.Text - 12.7) / 2) - 1.59 - 3)), 2)
Dim count As Decimal
count = SpaceLeftText.Text
If count > 10 Then
TenText.Text = Int(count / 10)
count = count - (TenText.Text * 10)
Else : TenText.Text = 0
End If
If count > 4 Then
FourText.Text = Int(count / 4)
count = count - (FourText.Text * 4)
Else : FourText.Text = 0
End If
If count > 2 Then
TwoText.Text = Int(count / 2)
count = count - (TwoText.Text * 2)
Else : TwoText.Text = 0
End If
If count > 1.5 Then
OnePointFiveText.Text = Int(count / 1.5)
count = count - (OnePointFiveText.Text * 1.5)
Else : OnePointFiveText.Text = 0
End If
If count > 1 Then
OneText.Text = Int(count / 1)
count = count - (OneText.Text * 1)
Else : OneText.Text = 0
End If
End Sub
Private Sub ResetButton_Click(sender As System.Object, e As System.EventArgs) Handles ResetButton.Click
AxleLengthText.Clear()
SpaceLeftText.Clear()
TenText.Clear()
FourText.Clear()
TwoText.Clear()
OnePointFiveText.Clear()
OneText.Clear()
GapText.Clear()
QuadRingText.Clear()
OringSpacerText.Clear()
FitText.Clear()
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
End Sub
End Class
所以我在Dim Count上面添加了以下代码作为十进制:
If SpaceLeftText.Text = "" Then
MsgBox("Please Enter Axle Length!")
Else
但现在一旦我运行它,没有按下输入并留下一个空白的输入框我立即得到我的消息框说“请输入轴长度”。我点击确定,然后在进入程序之前立即弹出大约14次。有没有人有任何意见。我不知道我做错了什么。 谢谢。
答案 0 :(得分:1)
由于您的事件正在处理(MyBase.Activated),因此该消息显示14次。
请尝试以下方法:
Private Sub EnterButton_Click(sender As Object, e As EventArgs) Handles EnterButton.Click
还要确保(AxleLengthText.Text)不为空,并且有效转换为double值,如下所示:
dim tmpDouble as double
if not string.isNullOrEmpty(AxleLengthText.Text) andalso Double.TryParse(AxleLengthText.Text, tmpDouble ) Then
SpaceLeftText.Text = Math.Round((((Val(tmpDouble - 12.7) / 2) - 1.59 - 3)), 2)
end If