在我的文本框中输入“ - ”我在Microsoft.VisualBasic.dll中发生System.InvalidCastException'

时间:2015-06-16 05:21:38

标签: vb.net visual-studio-2010

我在文本框中输入“ - ”时遇到问题我收到错误。有人可以告诉我这个代码块出了什么问题吗?

Private Sub HourBox_TextChanged(sender As Object, e As EventArgs) Handles HourBox.TextChanged
    Label10.Text = CStr(Val(CostBox.Text) * Val(AppBox.Text) * Val(HourBox.Text))
    If HourBox.Text >= 24 Then
        Label2.Visible = True
        Label2.ForeColor = Color.Red
        HourBox.Text = "0"
        Label2.Text = "Hours must be between 0 - 24." & vbNewLine & "Select your appliance and try again."
    ElseIf HourBox.Text < 0 Then
        Label2.Visible = True
        Label2.ForeColor = Color.Red
        HourBox.Text = "0"
        Label2.Text = "Hours must be between 0 - 24." & vbNewLine & "Select your appliance and try again."
    End If

1 个答案:

答案 0 :(得分:0)

你需要检查HourBox是否是一个数值,因为如果你想输入-10,那么事件将在 - ,然后再次在-1,最后在-10:

Private Sub HourBox_TextChanged(sender As Object, e As EventArgs) Handles HourBox.TextChanged
If IsNumeric(HourBox.Text) Then
    Label10.Text = CStr(Val(CostBox.Text) * Val(AppBox.Text) * Val(HourBox.Text))
    If HourBox.Text >= 24 Then
        Label2.Visible = True
        Label2.ForeColor = Color.Red
        HourBox.Text = "0"
        Label2.Text = "Hours must be between 0 - 24." & vbNewLine & "Select your appliance and try again."
    ElseIf HourBox.Text < 0 Then
        Label2.Visible = True
        Label2.ForeColor = Color.Red
        HourBox.Text = "0"
        Label2.Text = "Hours must be between 0 - 24." & vbNewLine & "Select your appliance and try again."
    End If
End If