当整数在有效平均值内时输入无效?

时间:2015-09-02 03:01:01

标签: vb.net vba

我正在研究VB程序,相当基本(没有双关语),我需要将基本整数转换为罗马数字。我的转换部分与我的Select Case完美配合。我还需要添加验证输入,因此如果输入的数字无效,则文本框会显示。 1到10之间的任何数字都应该能够单击转换按钮。目前,我在1到10之间输入的任何数字都会立即显示,“该数字无效。”

这是我当前的代码,但失败了:

Public Class Form1

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

End Sub

Private Sub lblRomanNum_Click(sender As Object, e As EventArgs)

End Sub

Private Sub txtBox1_TextChanged(sender As Object, e As EventArgs) Handles txtBox1.TextChanged
    Dim intNum As Integer
    If intNum < 1 Or intNum > 10 Then
        txtBox1.Text = "That number is invalid."
        'ElseIf intNum > 10 Then
        'txtBox1.Text = "That number is invalid"
    End If

End Sub

Private Sub txtBox2_TextChanged(sender As Object, e As EventArgs) Handles txtBox2.TextChanged

End Sub

Private Sub btnConvert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConvert.Click
Select CInt(txtBox1.Text)
        Case 1                      ' numerical 1
            txtBox2.Text = "I"
        Case 2                      ' numerical 2
            txtBox2.Text = "II"
        Case 3                      ' numerical 3
            txtBox2.Text = "III"
        Case 4                      ' numerical 4
            txtBox2.Text = "IV"
        Case 5                      ' numerical 5
            txtBox2.Text = "V"
        Case 6                      ' numerical 6
            txtBox2.Text = "VI"
        Case 7                      ' numerical 7
            txtBox2.Text = "VII"
        Case 8                      ' numerical 8
            txtBox2.Text = "VIII"
        Case 9                      ' numerical 9
            txtBox2.Text = "IX"
        Case 10                     ' numerical 10
            txtBox2.Text = "X"
            'Case Else
            'If a user enters an invalid value, this message is displayed and no conversion is attempted, according to instructions.
            'txtBox2.Text = "That value is invalid."
    End Select

End Sub

Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
    Me.Close()
End Sub

Private Sub lblRomanNum_Click_1(sender As Object, e As EventArgs)

End Sub
End Class

任何小于1的intNum都应显示无效消息。

任何大于10的intNum都应显示无效消息。

如果我正在阅读目前正确的内容,这应该可以使用,并允许我输入1到10之间的数字,而不会显示无效消息。我在这里错过了什么吗?

3 个答案:

答案 0 :(得分:1)

尝试使用括号和'或'

1. Dim intNum As Integer
2.    If (intNum < 1) or (intNum > 10) Then
3.        txtBox1.Text = "That number is invalid."
4.    End If

答案 1 :(得分:0)

您的代码在Visual Studio 2013中使用.NET Framework 4.5.1非常适合我。尝试删除整个块并重新键入代码。 或者你也可以尝试这个代码

 If intNum < 1 OrElse intNum > 10 Then
    TextBox1.Text = "That number is invalid."
 End If

答案 2 :(得分:0)

需要添加......

 Integer.TryParse(txtBox1.Text, i) 

...直接在我的变量声明下。