winforms 如何显示平均值计算器的MsgBoxes

5vf7fwbs  于 2023-10-23  发布在  其他
关注(0)|答案(1)|浏览(163)

我试图有错误消息显示,如果用户不插入任何数字,在字母或符号类型,如果他们在一个数字的类型不是在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))但它崩溃我的程序,而是显示一个错误,在我的程序说“从字符串转换“”类型''是无效的。

wmtdaxz3

wmtdaxz31#

程序崩溃是因为方法顶部的代码试图在完成验证之前进行计算(和数据类型转换),这意味着它可能会尝试转换无效值。
要解决这个问题,请不要进行计算或分配整数变量,直到 * 验证步骤之后 *,最好使用Integer.Parse(),然后 * 只有验证成功。
此外,您应该将验证抽象到一个方法中,以避免重复这么多代码,并且您应该 * 绝对 * 打开Option Strict

相关问题