我需要帮助显示平均值计算器的消息框。我该如何解决这个问题?

问题描述 投票:0回答:1

如果用户未插入任何数字、未输入字母或符号,或者输入的数字不在 1-100 之间,我会尝试显示错误消息。如果您添加值,GUI 工作正常,但尝试触发消息会使 GUI 崩溃。

这是我到目前为止所拥有的:

Private Sub btnCalcaulate_Click(sender As Object, e As EventArgs) Handles btnCalcaulate.Click

    Dim int_grade1 As Integer = TxtboxNum1.Text
    Dim int_grade2 As Integer = txtBoxNum2.Text
    Dim int_grade3 As Integer = txtBoxNum3.Text

    Dim int_avgGrade As Integer = (int_grade1 + int_grade2 + int_grade3) / 3

    lblAverageNum.Text = int_avgGrade




    If (TxtboxNum1.Text = "") Then
        MsgBox("Please Enter a Value for Number 1")
        TxtboxNum1.Focus()
        LblNumber1.ForeColor = Color.Red

    ElseIf IsNumeric(TxtboxNum1.Text) = False Then
        MsgBox("Number 1 value must be a number")
        TxtboxNum1.Focus()
        LblNumber1.ForeColor = Color.Red

    ElseIf TxtboxNum1.Text > 100 Or TxtboxNum1.Text < -1 Then
        MsgBox("Number 1 value must be between 1-100")
        TxtboxNum1.Focus()
        LblNumber1.ForeColor = Color.Red

    ElseIf (txtBoxNum2.Text = "") Then
        MsgBox("Please Enter a Value for Number 2")
        txtBoxNum2.Focus()
        lblNumber2.ForeColor = Color.Red

    ElseIf IsNumeric(txtBoxNum2.Text) = False Then
        MsgBox("Number 2 value must be a number")
        txtBoxNum2.Focus()

    ElseIf txtBoxNum2.Text > 100 Or txtBoxNum2.Text < -1 Then
        MsgBox("Number 2 value must be between 1-100")
        txtBoxNum2.Focus()
        lblNumber2.ForeColor = Color.Red

    ElseIf (txtBoxNum3.Text = "") Then
        MsgBox("Please Enter a Value for Number 3")
        txtBoxNum3.Focus()
        lblNumber3.ForeColor = Color.Red

    ElseIf IsNumeric(txtBoxNum3.Text) = False Then
        MsgBox("Number 3 value must be a number")
        txtBoxNum3.Focus()

    ElseIf txtBoxNum3.Text > 100 Or txtBoxNum3.Text < -1 Then
        MsgBox("Number 3 value must be between 1-100")
        txtBoxNum3.Focus()
        lblNumber3.ForeColor = Color.Red

    ElseIf lblAverageNum.Text >= 60 Then
        lblAverageNum.ForeColor = Color.Green

    ElseIf lblAverageNum.Text < 60 Then
        lblAverageNum.ForeColor = Color.Red
    Else
        int_grade1 = CInt(TxtboxNum1.Text)
        int_grade2 = CInt(txtBoxNum2.Text)
        int_grade3 = CInt(txtBoxNum3.Text)
        int_avgGrade = CInt(lblAverageNum.Text)




    End If
End Sub

虽然计算有效,但当我尝试激活错误消息(空格、输入字母或非数字、或数字不在 (0-100) 之间)时,它会导致我的程序崩溃,并在程序中显示错误说“从字符串”转换为“整数”类型无效

vb.net average sln-file
1个回答
0
投票

在验证步骤之后之前不要进行计算,并且只有在验证步骤成功时才进行计算。此外,您应该将验证抽象为一个方法,以避免重复代码,并且您应该一定打开

Option Strict

© www.soinside.com 2019 - 2024. All rights reserved.