Visual Basic错误消息

时间:2017-04-14 17:53:25

标签: vb.net

我是Visual Basic的新手所以我意识到这个问题是补救性的...当我尝试使用以下代码运行我的程序时,我收到以下错误消息:

  

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

     

其他信息:从字符串“”到“Double”类型的转换无效。

我意识到已经问过类似的问题,但是我想显示我的代码:

Private Sub txtGrade1_TextChanged(sender As Object, e As EventArgs) Handles txtGrade1.TextChanged

    Dim numGrade As Decimal

    numGrade = CDec(txtGrade1.Text * 0.15) + CDec(txtGrade2.Text * 0.25) + CDec(txtGrade3.Text * 0.2) + CDec(txtGrade4.Text * 0.4)
    MsgBox("Your Grade is" + numGrade)

End Sub

我不知道这里发生了什么。该程序将允许我在运行时在文本框中输入1位数,但后来我收到错误消息

1 个答案:

答案 0 :(得分:1)

好吧,这将解决您的类型不匹配问题。但您可能不希望每个时间txtGrade1.Text更改时都显示一个消息框

Private Sub txtGrade_TextChanged(sender As Object, e As EventArgs) Handles txtGrade1.TextChanged
    Dim grade1, grade2, grade3, grade4 As Double
    If Double.TryParse(txtGrade1.Text, grade1) _
            AndAlso Double.TryParse(txtGrade2.Text, grade2) _
            AndAlso Double.TryParse(txtGrade3.Text, grade3) _
            AndAlso Double.TryParse(txtGrade4.Text, grade4) Then
        Dim grade = grade1 * 0.15 + grade2 * 0.25 + grade3 * 0.2 + grade4 * 0.4
        MsgBox(String.Format("Your Grade is {0}", grade))
    End If
End Sub

要改进您的代码,您可以在任何TextBoxes 验证而不是更改时实现此目的,因为如果您输入的是99,则更改事件会在第一个之后触发键入9。当您离开TextBox

时,Validated处理程序将触发
Private Sub txtGradesValidated(sender As Object, e As EventArgs) _
        Handles txtGrade1.Validated, txtGrade2.Validated, txtGrade3.Validated, txtGrade4.Validated
    Dim grade1, grade2, grade3, grade4 As Double
    If Double.TryParse(txtGrade1.Text, grade1) _
            AndAlso Double.TryParse(txtGrade2.Text, grade2) _
            AndAlso Double.TryParse(txtGrade3.Text, grade3) _
            AndAlso Double.TryParse(txtGrade4.Text, grade4) Then
        Dim grade = grade1 * 0.15 + grade2 * 0.25 + grade3 * 0.2 + grade4 * 0.4
        MsgBox(String.Format("Your Grade is {0}", grade))
    End If
End Sub

仍然不理想,你会看到你测试它。你也可以考虑使用KeyPress或KeyUp,只在 Enter 上执行逻辑,但这会改变你的程序的逻辑和设计,所以它取决于你。