VB2010:允许文本框中的浮点数/整数,退格键和值范围

时间:2013-04-11 08:32:42

标签: vb.net visual-studio-2010


我在Visual Basic中有一个文本框(V​​isual Studio 2010,.net框架工作4.0)
现在我有问题!
我希望该用户只输入整数,浮点数,退格键和值范围?
困惑?
哦耶 我只希望该用户输入介于0 - 4之间的值(值可能是十进制的,为3.49)
现在我想要完整的代码:
我有这个:
这是有效的,但我无法指定0-4之间的范围

  

Private Sub TextBox1_KeyPress(ByVal sender As Object,ByVal e As   System.Windows.Forms.KeyPressEventArgs)处理TextBox1.KeyPress

        Dim FullStop As Char
        FullStop = "."

        ' if the '.' key was pressed see if there already is a '.' in the string
        ' if so, dont handle the keypress

        If e.KeyChar = FullStop And TextBox1.Text.IndexOf(FullStop) <> -1 Then
            e.Handled = True
            Return
        End If

        ' If the key aint a digit
        If Not Char.IsDigit(e.KeyChar) Then
            ' verify whether special keys were pressed
            ' (i.e. all allowed non digit keys - in this example
            ' only space and the '.' are validated)
            If (e.KeyChar <> FullStop) And
               (e.KeyChar <> Convert.ToChar(Keys.Back)) Then
                ' if its a non-allowed key, dont handle the keypress
                e.Handled = True
                Return
            End If
        End If
End Sub


如果有人给我完整的代码,那么我将非常高兴 提前致谢

1 个答案:

答案 0 :(得分:1)

我刚刚使用了ascii codes characters的好处来解决您的问题, 试试这个,如果您对以下实施有任何疑问,请随时回复我。

 Private Sub TextBox1_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress

        'Ascii code 8 for backspace -- Ascii code 46 for (. period)
        If Asc(e.KeyChar) = 8 Or Asc(e.KeyChar) = 46 Then

            'If typed character is a period then we have to ensure that more than one of it
            'Should not get allowed to type. And also we have to check whether the period symbol
            'may cause any conflicts with MaxNo that is 4
            If Asc(e.KeyChar) = 46 Then
                If TextBox1.Text.IndexOf(".") <> -1 Or Val(TextBox1.Text.Trim & e.KeyChar) >= 4 Then
                    e.Handled = True
                Else
                    Exit Sub
                End If
            Else
                'If pressed key is backspace, then allow it.
                Exit Sub
            End If

        End If

        'Checking whether user typing more than 4 or not.
        If Val(TextBox1.Text.Trim & e.KeyChar) > 4 Then
            e.Handled = True
        End If

        '48 - 57  = Ascii codes for numbers
        If (Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57) Then
            e.Handled = True
        End If

    End Sub