字段为空时出现Visual Basic错误



我的表单在调试时崩溃,并返回错误:

System.InvalidCastException:'从字符串"到类型'Integer'的转换无效。'

这是我认为问题发生的代码:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim decdays As Integer
Dim decmedication As Decimal
Dim decsurgical As Decimal
Dim declabfee As Decimal
Dim decphysical As Decimal
Dim x As String
TextBox1.Focus()
decdays = CInt(TextBox1.Text)
decmedication = CDec(TextBox2.Text)
decsurgical = CDec(TextBox3.Text)
declabfee = CDec(TextBox4.Text)
decphysical = CDec(TextBox5.Text)
Dim charges As Decimal
Dim totalMischarges As Decimal
TextBox1.Focus()
If decdays < 0 Then
x = "Length of days should be numeric and positive"
Label1.Text = x.ToString()
ElseIf decmedication < 0 Then
x = "Medication charges should be numeric and positive"
Label2.Text = x.ToString()
ElseIf decsurgical < 0 Then
x = "Surgical charges should be numeric and positive"
Label3.Text = x.ToString()
ElseIf declabfee < 0 Then
x = "Lab fees should be numeric and positive"
Label4.Text = x.ToString()
ElseIf decphysical < 0 Then
x = "Physical charges should be numeric and positive"
Label5.Text = x.ToString()
Else
charges = CalcStayCharges(decdays)
totalMischarges = CalcMisCharges(decmedication, decsurgical, declabfee, decphysical)
dectotalcost = CalcTotalCharges(charges, totalMischarges)
TextBox6.Text = "$" + dectotalcost.ToString()
End If
End Sub

我试过TryParse(),但它不起作用!

所有这些字段都需要文本框中的有效值才能工作。错误消息解释您遇到的问题。

如果您的文本框可以接受来自用户的任何内容,那么在使用之前应该验证您的输入。如果您使用下面演示的TryParse模式,它还会设置验证后使用的变量。

这些代码行:

decdays = CInt(TextBox1.Text)
decmedication = CDec(TextBox2.Text)
decsurgical = CDec(TextBox3.Text)
declabfee = CDec(TextBox4.Text)
decphysical = CDec(TextBox5.Text)

应该转换成这样的东西:

Dim decdays As Integer
Dim decmedication As Decimal
Dim decsurgical As Decimal 
Dim declabfee As Decimal 
Dim decphysical As Decimal 
If Not Integer.TryParse(TextBox1.Text, decdays) Then
messagebox.show("Textbox1 text is Not valid")
Return
End If
If Not Decimal.TryParse(TextBox2.Text, decmedication) Then
messagebox.show("Textbox2 text is Not valid")
Return
End If
If Not Decimal.TryParse(TextBox3.Text, decsurgical) Then
messagebox.show("Textbox3 text is Not valid")
Return
End If
If Not Decimal.TryParse(TextBox4.Text, declabfee) Then
messagebox.show("Textbox4 text is Not valid")
Return
End If
If Not Decimal.TryParse(TextBox5.Text, decphysical) Then
messagebox.show("Textbox5 text is Not valid")
Return
End If

最新更新