0


我在 Visual Basic 中有一个文本框(V​​isual Studio 2010,.net frame work 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


如果有人给我完整的代码,我会很高兴
提前谢谢

4

1 回答 1

1

我只是使用 的 的好处ascii codescharacters解决您的问题,试试这个,如果您对以下实现有任何疑问,请随时给我评论。

 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
于 2013-04-11T10:07:48.953 回答