如果用户没有输入整数,如何向程序添加错误消息?

时间:2015-05-17 17:54:33

标签: vb.net

我正在用Visual Basic编程,正在创建一个平均计算器。如果用户在文本框中输入除整数之外的任何内容,我需要合并的一件事是错误消息。我的代码看起来像这样。

Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
        txtAverage.Text = Str((Val(txtTextBox1.Text) + Val(txtTextBox2.Text) + Val(txtTextBox3.Text) + Val(txtTextBox4.Text) + Val(txtTextBox5.Text)) / 5)

    End Sub

    Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
        txtTextBox1.Text = ""
        txtTextBox2.Text = ""
        txtTextBox3.Text = ""
        txtTextBox4.Text = ""
        txtTextBox5.Text = ""

    End Sub

    Private Sub btnCancel_Click(sender As Object, e As EventArgs) Handles btnCancel.Click
        Me.Close()

    End Sub

End Class

1 个答案:

答案 0 :(得分:0)

您可以验证输入并计算平均值。

创建一个包含要验证的所有TextBox的数组,然后循环遍历数组的元素。对于每个TextBox,使用Integer.TryParse检查内容是否有效,如果是,则转换为整数。如果内容无效,则显示MessageBox并退出Sub。各个数字被添加到一个名为total的整数中,最终用于计算平均值。

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
    Dim boxes() As TextBox = {txtTextBox1, txtTextBox2, txtTextBox3, txtTextBox5, txtTextBox5}
    Dim total As Integer
    For Each box As TextBox In boxes
        Dim num As Integer
        If Integer.TryParse(box.Text, num) Then
            total += num
        Else
            MessageBox.Show("Invalid number in " & box.Name)
            Exit Sub
        End If
    Next
    Dim average As Double = total / boxes.Length
    txtAverage.Text = average.ToString
End Sub