文本框为空时System.InvalidCastException

时间:2015-06-10 05:59:28

标签: vb.net

当我输入第一个文本框,将其他文本框留空时,我收到此错误:

  

Microsoft.VisualBasic.dll中出现未处理的“System.InvalidCastException”类型异常“

Public Class myProject_P2

Public Sub CostPerKWH_TextChanged(sender As Object, e As EventArgs) Handles CostPerKWH.TextChanged
    Dim CostPerkwh_Value As Integer = CostPerKWH.Text
    Dim Appliancekwh_Value As Integer = ApplianceKWH.Text
    Dim HourPerDay_Value As Integer = HoursPerDay.Text
    Dim EnergyConsumption_Value As Integer = EnergyConsumptio.Text

    EnergyConsumption_Value = CostPerkwh_Value * Appliancekwh_Value * HourPerDay_Value
End Sub

End Class

2 个答案:

答案 0 :(得分:0)

我真的不知道您的程序流程,但如果您的问题只是问题System.InvalidCastException中说明的错误,请尝试下面粘贴的代码。

在其他任何事情之前, 它抛出该错误的原因可能是您在第一个字段上键入,而其他人为空,其中第一个字段被编程为在文本更改时,其他值字段将被传递或分配给整数变量。因此,由于它们为空,因此传递的值为""值或empty string值。分配给整数的字符串值肯定会导致错误。在传递值之前尝试验证,我建议不要在文本更改中放置赋值,而是尝试添加button并在那里添加代码。点击按钮后,流程将继续:

Dim CostPerkwh_Value As Integer
Dim Appliancekwh_Value As Integer
Dim HourPerDay_Value As Integer
Dim EnergyConsumption_Value As Integer

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    If IsNumeric(CostPerKWH.Text) And IsNumeric(ApplianceKWH.Text) _
        And IsNumeric(HoursPerDay.Text) And IsNumeric(EnergyConsumptio.Text) Then
        CostPerkwh_Value = CostPerKWH.Text
        Appliancekwh_Value = ApplianceKWH.Text
        HourPerDay_Value = HoursPerDay.Text
        EnergyConsumption_Value = EnergyConsumptio.Text

        EnergyConsumption_Value = CostPerkwh_Value * Appliancekwh_Value * HourPerDay_Value
        MsgBox(EnergyConsumption_Value)
    Else
        MsgBox("Some inputs are not in numeric.")
    End If
End Sub

答案 1 :(得分:0)

另一种解决方案是:

if TryCast(Textboxt1.text, integer) then
   ' do something
end if

MSDN TryCast Documentation