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

时间:2016-04-21 16:14:35

标签: vb.net visual-studio-2010

只要用户正确输入信息,我就编写了一个完美的代码。如果用户确实在文本框中输入了数字,则会显示一条错误消息,告知用户必须输入数据。当发生这种情况时,我得到一个强制转换异常:

  

抛出异常:' System.InvalidCastException'在Microsoft.VisualBasic.dll

中      

其他信息:从字符串转换""输入'整数'无效。

我是新手,我很感激任何建议。

此行发生异常:

intDetermineSubTotalCost(intSiteSelected, CInt(txtNumberOfNights.Text))

如果我删除严格选项,它将适用于预期的对话,但是项目要求它开启。

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

4 个答案:

答案 0 :(得分:2)

您可以查看类似的内容,以限制他们输入非数字按键。

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

答案 1 :(得分:2)

Just Do some input checking before your perform you calculations. For Example A Textbox requiring Input:

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

Or

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

This Stops the code crashing if there is an error and gives the user the opportunity to fix their input. Once all the input has been checked, perform your calculations.

答案 2 :(得分:1)

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

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

答案 3 :(得分:1)

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

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