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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/938329/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 14:14:46  来源:igfitidea点击:

How to filter textbox input to numeric only?

vb.net

提问by Tom

How do I suppress all data except numeric?

如何抑制除数字以外的所有数据?

This is not working on KeyDown():

这不适用于KeyDown()

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

回答by kevchadders

There are many ways to do this. I've had a quick stab at it and go this which works. I have used the KeyPress sub for the textbox, and pass each keypress to the IsNumber function.

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

NOTE: I have allowed the backspace key to be used in case you make a mistake with the numbers and want to deleted.

注意:我允许使用退格键,以防您输入错误并想删除数字。

Take out the If e.KeyChar <> ChrW(Keys.Back) Then / End Ifpart if you dont need the backspace.

如果您不需要退格键,请取出If e.KeyChar <> ChrW(Keys.Back) Then / End If部分。

    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

回答by Josh

You can check Char.IsDigit(e.KeyChar), but the best thing to do in this case is to create a subclass of TextBox and override IsInputChar(). That way you have a reusable TextBox control that you can drop anywhere so you don't have to re-implement the logic.

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

(My VB is a bit rusty...)

(我的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

回答by Duke49ifrance

Will help you...

会帮助你...

    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

For use my function add this code into a textbox_keypress:

为了使用我的函数,将此代码添加到 textbox_keypress 中:

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

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

回答by Duke49ifrance

 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

回答by Laxmikant Bhumkar

This code will help you to restrict multiple TEXTBOXto accept only NUMERIC VALUEand BACKSPACE key. However you can remove If e.KeyChar <> ChrW(Keys.Back) Thenand End Ifvalue from code when you don't want to accept backspace key. Enhanced version of the kevchadderssolution in this thread.

此代码将帮助您限制多个TEXTBOX仅接受NUMERIC VALUE和 BACKSPACE 键。但是,当您不想接受退格键时,您可以从代码中删除If e.KeyChar <> ChrW(Keys.Back) ThenEnd If值。此线程中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

回答by user2219334

This will allow numeric input ,Backspace to correct your input , and also a decimal point.

这将允许数字输入,退格键来更正您的输入,以及小数点。

    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

回答by Ejie Fernandez

This is another way to restrict number inputs into textbox . using KEYPRESS Events

这是将数字输入限制到 textbox 的另一种方法。使用 KEYPRESS 事件

If Asc(e.KeyChar) <> 13 AndAlso Asc(e.KeyChar) <> 8 AndAlso Not IsNumeric(e.KeyChar) Then MessageBox.Show("Only Numbers") e.Handled = True End If End Sub hope it helps ! thnks ..

If Asc(e.KeyChar) <> 13 AndAlso Asc(e.KeyChar) <> 8 AndAlso Not IsNumeric(e.KeyChar) Then MessageBox.Show("Only Numbers") e.Handled = True End If End Sub 希望它有帮助!谢谢..

回答by Jon Milliken

The purpose of your function could help provide additional solutions. Checking for a numeric value on each KeyPress is likely overkill. Then you have to overkill it more by accounting for backspace, delete, copy, paste, etc.

您的函数的目的可以帮助提供其他解决方案。检查每个 KeyPress 上的数字值可能有点矫枉过正。然后你必须通过考虑退格、删除、复制、粘贴等来过度使用它。

For example, if you are storing a telephone number, you should use the "IsNumeric" function on the validate and update step. Alternatively, if you are selecting quantity of an item "NumericUpDown" control would be more appropriate than a TextBox.

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

回答by aslisabanci

I suggest that you use regular expressions. You can search Google, like 'regular expression textbox only numeric' and I guess you'll come up with many examples.

我建议你使用正则表达式。你可以搜索谷歌,比如“regular expression textbox only numeric”,我想你会想出很多例子。

For example, if you are in ASP.NET you can do it like:

例如,如果您在 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>