无效转换 - 转换异常:'System.InvalidCastException'

Invalid Conversion - Cast Exception: 'System.InvalidCastException'

我编写了一个代码,只要用户正确输入信息,它就可以完美运行。如果用户确实在文本框中输入了数字,我会收到一条错误消息,告诉用户必须输入数据。发生这种情况时,我得到一个转换异常:

Exception thrown: 'System.InvalidCastException' in Microsoft.VisualBasic.dll

Additional information: Conversion from string "" to type 'Integer' is not valid.

我是新手,如果有任何建议,我将不胜感激。

异常发生在这一行:

intDetermineSubTotalCost(intSiteSelected, CInt(txtNumberOfNights.Text))

如果我删除 strict on 选项,它将与预期的对话一起工作,但项目要求它打开。

Dim intSiteSelected As Double
Dim intNumberOfNights As Integer
Dim blnNightsStayingIsVaild As Boolean = False
Dim blnDiscountIsSelected As Boolean = False
Dim intDiscountChoice As Integer
Dim strDiscountSelected As String = ""

'   Call a function to confirm if the Number of Nights staying is valid.
blnNightsStayingIsVaild = ValidateNightsStaying()

'   call a function to confirm a discount has been seected.
intDiscountChoice = ValidateSelectedDiscount(blnDiscountIsSelected, strDiscountSelected)

'   If number of nights staying and available discount has been selected,
'   calculate the subtotal, tax, and final cost.
If (blnNightsStayingIsVaild And blnDiscountIsSelected) Then
    intNumberOfNights = Convert.ToInt32(txtNumberOfNights.Text)
    intSiteSelected = Me.cmbSelectASite.SelectedIndex
End If


If cmbSelectASite.SelectedIndex = 0 Then
    intSiteSelected = 20D
ElseIf cmbSelectASite.SelectedIndex = 1 Then
    intSiteSelected = 35D
ElseIf cmbSelectASite.SelectedIndex = 2 Then
    intSiteSelected = 55D
End If

intDetermineSubTotalCost(intSiteSelected, CInt(txtNumberOfNights.Text))


Private Function ValidateNightsStaying() As Boolean

'   This function validate the value entered for the number of nights staying in campground.
Dim intNightsStaying As Integer
Dim blnValidityCheck As Boolean = False
Dim StrNumberOfNightsErrorMessage As String =
    "Please Enter The Number Of Nights You Are Staying (1-99)"
Dim strMessageBoxTitle As String = " You Must Choose Number Of Nights"

Try
    intNightsStaying = Convert.ToInt32(txtNumberOfNights.Text)
    If intNightsStaying > 0 And intNightsStaying < 100 Then
        blnValidityCheck = True
    Else
        MsgBox(StrNumberOfNightsErrorMessage, , strMessageBoxTitle)
        blnValidityCheck = True
    End If
Catch Exception As FormatException
    MsgBox(StrNumberOfNightsErrorMessage, , strMessageBoxTitle)
    txtNumberOfNights.Focus()
    txtNumberOfNights.Clear()
Catch execption As OverflowException
    MsgBox(StrNumberOfNightsErrorMessage, , strMessageBoxTitle)
    txtNumberOfNights.Focus()
    txtNumberOfNights.Clear()
Catch execption As SystemException
    MsgBox(StrNumberOfNightsErrorMessage, , strMessageBoxTitle)
    txtNumberOfNights.Focus()
    txtNumberOfNights.Clear()
End Try
Return blnValidityCheck

End Function

有几种方法可以解决这个问题。

  1. 您可以检查字符串是否为空并对其进行验证。
  2. 将转换更改为 IIRC 将 return 0 为空的 TryParse
  3. 如果可能,将输入从文本框更改为数字 up/down 控件,最小值和最大值分别为 1 和 99。

你可以看看这样的东西,它会限制他们输入非数字按键。

Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress

'97 - 122 = Ascii codes for simple letters
'65 - 90  = Ascii codes for capital letters
'48 - 57  = Ascii codes for numbers

If Asc(e.KeyChar) <> 8 Then
    If Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57 Then
        e.Handled = True
    End If
End If

End Sub

只需在执行计算之前进行一些输入检查。 例如需要输入的文本框:

        If txtInput.text.Contains("whatever you don't want there") Then
           MessageBox.Show("Please Enter The Correct Info")
           txtInput.Focus()
           Return
        End if

        If Integer.TryParse(txtInput.Text, input) Then
            MessageBox.Show("Please Enter Some Text.")
            txtInput.Focus()
            Return
        End If

这会阻止代码在出现错误时崩溃,并让用户有机会修复他们的输入。检查完所有输入后,执行计算。

将您的 TextBox 更改为 Masked TextBox。掩码中只允许数字。

https://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox%28v=vs.110%29.aspx