字段留空时的Visual Basic错误

时间:2018-12-07 23:20:02

标签: vb.net

我去调试时出现错误,表单崩溃:

  

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(),但没有用!

1 个答案:

答案 0 :(得分:4)

所有这些字段均需要在文本框中输入有效值才能使用。错误消息说明了您遇到的问题。

如果文本框可以接受用户的任何东西,则应在使用之前验证输入内容。如果您使用下面演示的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
相关问题