如何仅将文本框输入过滤为数字?

时间:2009-06-02 07:32:54

标签: vb.net

如何取消除数字以外的所有数据?

这不适用于KeyDown()

If e.KeyData < Keys.D0 Or e.KeyData > Keys.D9 Then
    e.Handled = True
End If

9 个答案:

答案 0 :(得分:6)

有很多方法可以做到这一点。我已经快速刺了一下,然后就可以了。我已经将KeyPress子用于文本框,并将每个按键传递给IsNumber函数。

注意:我已经允许使用退格键,以防你输入数字并想要删除。

取出如果e.KeyChar&lt;&gt; ChrW(Keys.Back)然后/结束如果部分,如果你不需要退格。

    Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
    If e.KeyChar <> ChrW(Keys.Back) Then
        If Char.IsNumber(e.KeyChar) Then
        Else
            e.Handled = True
        End If
    End If
End Sub

答案 1 :(得分:5)

你可以查看Char.IsDigit(e.KeyChar),但在这种情况下最好的办法是创建一个TextBox的子类并覆盖IsInputChar()。这样你就可以使用可重复使用的TextBox控件,你可以放在任何地方,这样你就不必重新实现逻辑。

(我的VB有点生锈......)

Public Class NumericTextBox : Inherits TextBox

    Protected Overrides Function IsInputChar(Byval charCode As Char) As Boolean
        If (Char.IsControl(charCode) Or Char.IsDigit(charCode)) Then
            Return MyBase.IsInputChar(charCode)
        Else
            Return False
        End If
    End Function

End Class

答案 2 :(得分:1)

此代码可帮助您限制多个 TEXTBOX 仅接受 NUMERIC VALUE 和BACKSPACE键。但是,您可以删除如果e.KeyChar&lt;&gt;当您不想接受退格键时,ChrW(Keys.Back)然后结束来自代码的值。此线程中 kevchadders 解决方案的增强版本。

Private Sub TextBox_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress, TextBox2.KeyPress, TextBox3.KeyPress
    If e.KeyChar <> ChrW(Keys.Back) Then
        If Char.IsNumber(e.KeyChar) Then
        Else
            e.Handled = True
        End If
    End If
End Sub

答案 3 :(得分:1)

会帮助你......

    Public Function IsNumericTextbox(ByVal sender As TextBox, ByVal KeyChar As Char) As Boolean
    'set TRUE: cause a exception when the keychar is not Allowed into vars: allowedChars, allowedOneChar, allowedExceptionChar
    Dim UseThrowDebuggy As Boolean = False

    Dim allowedChars As String = "0123456789"
    Dim allowedOnceChar As Char() = {"."}
    Dim allowedExceptionChar As Keys() = {Keys.Back}

    Dim idxAllowedNotFound As Integer
    Dim idxCountOne As Integer = 0

    idxAllowedNotFound = allowedChars.IndexOf(KeyChar)
    If idxAllowedNotFound = True Then
        'AllowedOnce
        For Each _c As Char In allowedOnceChar
            If _c = KeyChar Then
                'Count Check
                For Each _cc As Char In sender.Text
                    If _c = _cc Then idxCountOne += 1
                Next
                If idxCountOne = 0 Then
                    Return False
                Else
                    Return True
                End If
            End If
        Next
        'Exceptions
        For i As Integer = 0 To allowedExceptionChar.Count - 1
            If Asc(KeyChar) = Convert.ToUInt32(allowedExceptionChar(i)) Then Return False
        Next
        'Not Throw
        If UseThrowDebuggy = False Then
            If Char.IsNumber(KeyChar) Then
                Return False
            Else
                Return True
            End If
        End If
        'Outside to end for throw
    Else
        'AllowedChars
        Return False
    End If

    Dim _kc As String = ControlChars.NewLine & "Char: " & KeyChar & ControlChars.NewLine & "Asc: " & Asc(KeyChar) & ControlChars.NewLine
    Throw New Exception("UseThrowDebuggy found a unknow KeyChar: " & _kc)
End Function

使用我的函数将此代码添加到textbox_keypress:

  

e.Handled = IsNumericTextbox(sender,e.KeyChar)

答案 4 :(得分:1)

 Public Class NumericTextBox : Inherits System.Windows.Forms.TextBox

 Protected Overrides Sub OnKeyPress(e As Windows.Forms.KeyPressEventArgs)
      If Char.IsDigit(e.KeyChar) Or
          Char.IsControl(e.KeyChar) Or
          e.KeyChar = lobalization.CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator Then
      MyBase.OnKeyPress(e)
    Else
        e.Handled = True
    End If
 End Sub

 End Class

答案 5 :(得分:0)

我建议您使用正则表达式。您可以搜索Google,例如“正则表达式文本框仅限数字”,我想您会想出很多示例。

例如,如果你在ASP.NET中,你可以这样做:

<asp:TextBox 
    ID="txtPhoneNumber" 
    runat="server" 
    Text='<%#Bind("phoneNumber") %>' 
    MaxLength="15">
</asp:TextBox>

<asp:RegularExpressionValidator 
    ID="rfvUSerPhoneNumberValidate" 
    runat="server"
    ControlToValidate="txtPhoneNumber" 
    Display="Dynamic" 
    ValidationExpression="^[0-9]{1,15}$"
    ErrorMessage="Please enter only numeric value for Phone Number" 
    EnableViewState="true">
</asp:RegularExpressionValidator>

答案 6 :(得分:0)

这将允许数字输入,Backspace校正您的输入,以及小数点。

    If (e.KeyChar < "0" OrElse e.KeyChar > "9") AndAlso e.KeyChar <> ControlChars.Back AndAlso e.KeyChar <> ControlChars.Cr AndAlso e.KeyChar <> "." Then
        Beep()
        e.Handled = True
    End If

答案 7 :(得分:0)

这是将数字输入限制为文本框的另一种方法。使用KEYPRESS事件

如果Asc(e.KeyChar)&lt;&gt; 13 AndAlso Asc(e.KeyChar)&lt;&gt; 8并且不是IsNumeric(e.KeyChar)然后             MessageBox.Show(“只有数字”)             e.Handled = True         万一     结束子 希望能帮助到你 ! thnks ..

答案 8 :(得分:0)

您的功能的目的可以帮助提供其他解决方案。检查每个KeyPress上的数值可能有点过分。然后你必须通过考虑退格,删除,复制,粘贴等来解决它。

例如,如果要存储电话号码,则应在验证和更新步骤中使用“IsNumeric”功能。或者,如果您选择项目数量“NumericUpDown”,则控制将比TextBox更合适。