简体   繁体   English

如何允许用户只在vb.net的文本框中输入数字?

[英]How to allow user to enter only numbers in a textbox in vb.net?

How can I prevent the user to enter characters but only numbers and '.' 如何阻止用户输入字符,但只能输入数字和'。' in a textbox in vb.net 2005? 在vb.net 2005的文本框中?

The following will allow you to test for specific key values (from http://www.daniweb.com/forums/thread127299.html ): 以下内容允许您测试特定的键值(来自http://www.daniweb.com/forums/thread127299.html ):

Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
    If (Microsoft.VisualBasic.Asc(e.KeyChar) < 48) _
              Or (Microsoft.VisualBasic.Asc(e.KeyChar) > 57) Then
            e.Handled = True
    End If
    If (Microsoft.VisualBasic.Asc(e.KeyChar) = 8) Then
            e.Handled = False
    End If
End Sub

If this isn't what you are looking for, try the isNumeric() function. 如果这不是您要找的,请尝试使用isNumeric()函数。

Just to help, I had a snippet which I was making for a calculator which may help, it allows Delete, Backspace, Digits and the '.' 只是为了帮助,我有一个片段,我正在制作一个可能有用的计算器,它允许删除,退格,数字和'。' char. 焦炭。 You can also add in a call to a function to process the text box on the pressing of the Enter key. 您还可以添加对函数的调用,以便在按Enter键时处理文本框。

  Private Sub Box_Input_KeyDown(ByVal sender As Object, _
                                ByVal e As System.Windows.Forms.KeyEventArgs) _
                                Handles Box_Input.KeyDown



    If Char.IsDigit(Chr(e.KeyValue)) Or _
       Chr(e.KeyValue) = "¾"c Or _
       e.KeyData = Keys.Delete Or _
       e.KeyData = Keys.Back Then

        If Chr(e.KeyValue) = "¾"c Then
            If Box_Input.Text.Contains(".") Then
                e.SuppressKeyPress = True
            Else
                e.SuppressKeyPress = False
            End If
        End If
    ElseIf e.KeyData = Keys.Enter Then
         `State a call to function for when Enter is pressed`
    Else
        e.SuppressKeyPress = True
    End If

End Sub

This code allows entry of all numbers, the back space and delete keys as well as only allowing one '.' 此代码允许输入所有数字,后退空格和删除键以及仅允许一个'。' in the text. 在文中。 An idea might be to add the TAB function to allow Tab stops. 一个想法可能是添加TAB功能以允许Tab停止。

Dim num1 As Integer

Try   

   num1 = Cint(TextBox1.Text)

Catch ex As Exception

   TextBox1.Clear()    
   TextBox1.Focus()

End Try

For Single Numbers you may use num1 = Csng(textbox1.text) 对于单个数字,您可以使用num1 = Csng(textbox1.text)

try this; 尝试这个;

 Dim Validinputchar = "0123456789." + vbBack

    If Not Validinputchar.Contains(e.KeyChar) Then

        e.KeyChar = Nothing

    End If

The Validinputchar variable contains only the characters you want a user to enter in a textbox. Validinputchar变量仅包含您希望用户在文本框中输入的字符。

Note: the code should be placed under the textbox_keypress event 注意:代码应放在textbox_keypress事件下

Try this: 尝试这个:

Sub TB_Press(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress
    If Not Char.IsDigit(e.KeyChar) AndAlso Not Char.IsControl(e.KeyChar) Then
        e.Handled = True
    End If
End Sub

But this allow only numbers, and you may what to admit decimal digits adding this condition: 但是这只允许数字,你可以接受添加这个条件的十进制数字:

If e.KeyChar <> decSeparator AndAlso _
                     Not CType(sender, TextBox).Text.Contains(decSeparator) Then

You can get the decimal separator with: 你可以得到小数分隔符:

Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSepar‌​ator

Another simple option is to do this: 另一个简单的选择是这样做:

Sub TB_Press(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress
    Dim text As String = Ctype(sender, TextBox).Text
    e.Handled = Double.TryParse(text, New Double)
End Sub

I wrote a fool proof routine that eliminates the Alpha characters and allows all of the others. 我写了一个傻瓜证明程序,它消除了Alpha字符并允许所有其他字符。

You could technically put any character you want in the string to prevent it from being entered like punctuation marks. 您可以在技术上将所需的任何字符放在字符串中,以防止它像标点符号一样输入。

    Private Sub checkIfNumber(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles tbReOrderAmount.KeyDown

    Dim disallowedKeys As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
    If Boolean.Parse(disallowedKeys.Contains(e.KeyCode.ToString)) Then
        e.SuppressKeyPress = True
    End If
End Sub

This is a nice clean simple way of preventing any character in the disallowedKeys string from being entered in any textbox or field you choose, just have the KeyDown event of the control reference this method. 这是一种很好的简洁方法,可以防止在您选择的任何文本框或字段中输入disallowedKeys字符串中的任何字符,只需让控件的KeyDown事件引用此方法即可。

Here is the Better Answer in My Opinion: 以下是我的意见中的更好答案:

   Private Sub txtScale_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtScale.KeyPress
          If IsNumeric(txtScale.Text + e.KeyChar) = False Then e.Handled = True
   End Sub

Cheers,Sach 欢呼声,萨克斯

After searching through several results here on stackoverflow and elsewhere I wasn't satisfied with the solutions I found: they all had drawbacks of some sort, mostly keyboard layout issues or incorrect handling of control keys, eg Ctrl+C wasn't possible anymore. 在stackoverflow和其他地方搜索了几个结果后,我对我发现的解决方案不满意:它们都有某种缺点,主要是键盘布局问题或控制键处理不正确,例如Ctrl + C不再可能。

The solutions I tried all went for the KeyDown/Up approach; 我尝试过的解决方案都采用了KeyDown / Up方法; I decided to try the TextChanged event and implementing the simple logic: if the current input doesn't validate, then replace it with the old value; 我决定尝试TextChanged事件并实现简单逻辑:如果当前输入未验证,则将其替换为旧值; else: update the old value. else:更新旧值。

Of course - as always - implementing the feature details turned out to be a bit more complex :o| 当然 - 一如既往 - 实现功能细节变得有点复杂:o | ...but in the end I now have a TextBox that can be limited to integer or double values within a specified range and that has a new event, ApplyValue, that can be listened to - instead of TextChanged or Validated - which is fired depending on the chosen style, ie numeric values shouldn't fire events while typing, but for some text values it may be desirable. ...但最后我现在有一个TextBox,它可以限制在指定范围内的整数或双精度值,并且有一个新事件,ApplyValue,可以被监听 - 而不是TextChanged或Validated - 这是取决于在所选择的样式上,即数字值不应在键入时触发事件,但对于某些文本值,可能需要。

'nuff said, here's the full code of the control that I'd like to share with the absolutely amazing stackoverflow community - my first contribution ;o) I hope it can be of some use to someone! 'nuff说,这里是控件的完整代码,我想与绝对惊人的stackoverflow社区分享 - 我的第一个贡献; o)我希望它对某人有用!

Imports System.ComponentModel

Public Class RestrictedTextbox
    Inherits Windows.Forms.TextBox

#Region "Constructor, StyleEnum, ApplyValue event"
    Public Sub New()
        MyBase.New()
    End Sub

    'use enum instead of flags because of the overhead for creating a UiTypeEditor
    Public Enum StyleEnum
        [Integer]
        IntegerZero
        [Double]
        DoubleZero
        TextOnChange
        TextOnValidate
    End Enum

    Public Event ApplyValue(sender As Object, e As System.EventArgs)
#End Region

#Region "New Properties"
    Private _style As StyleEnum = StyleEnum.TextOnValidate
    <Category("Restrictions"), _
     Description("Determines input validation, alignment and when the ApplyValue event is raised"), _
     Browsable(True), DefaultValue(StyleEnum.TextOnValidate)> _
    Public Shadows Property Style As StyleEnum
        Get
            Return _style
        End Get
        Set(value As StyleEnum)
            _style = value

            initializeText()
        End Set
    End Property

    Private _min As Integer = 0
    <Category("Restrictions"), _
     Description("Minimum value (for numeric styles)"), _
     Browsable(True), DefaultValue(0)> _
    Public Property Minimum As Integer
        Get
            Return _min
        End Get
        Set(value As Integer)
            _min = value

            initializeText()
        End Set
    End Property

    Private _max As Integer = 2147483647
    <Category("Restrictions"), _
     Description("Maximum value (for numeric styles)"), _
     Browsable(True), DefaultValue(2147483647)> _
    Public Property Maximum As Integer
        Get
            Return _max
        End Get
        Set(value As Integer)
            _max = value

            initializeText()
        End Set
    End Property
#End Region

#Region "Shadow properties"
    'hide and do not allow changing
    <Browsable(False), EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)> _
    Public Shadows Property TextAlign As Windows.Forms.HorizontalAlignment
        Get
            Return MyBase.TextAlign
        End Get
        Set(value As Windows.Forms.HorizontalAlignment)
            'do nothing
        End Set
    End Property

    'hide and always use false
    <Browsable(False), EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)> _
    Public Shadows Property Multiline As Boolean
        Get
            Return False
        End Get
        Set(value As Boolean)
            MyBase.Multiline = False
        End Set
    End Property

    'hide and always use true
    <Browsable(False), EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)> _
    Public Shadows Property CausesValidation As Boolean
        Get
            Return True
        End Get
        Set(value As Boolean)
            MyBase.CausesValidation = True
        End Set
    End Property

    'hide, but emulate default
    <Browsable(False), EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)> _
    Public Shadows Property Lines As String()
        Get
            Return MyBase.Lines
        End Get
        Set(value As String())
            MyBase.Lines = value
        End Set
    End Property
#End Region

#Region "validateText, initializeText"
    Private _oldText As String = ""
    Private nfi As System.Globalization.NumberFormatInfo = New System.Globalization.NumberFormatInfo With {.CurrencyDecimalSeparator = "."}

    Private Sub initializeText()
        Dim def As String = ""

        Select Case _style
            Case StyleEnum.TextOnChange, StyleEnum.TextOnValidate
                MyBase.TextAlign = HorizontalAlignment.Left
                def = ""

            Case StyleEnum.Double, StyleEnum.Integer
                MyBase.TextAlign = HorizontalAlignment.Right
                def = ""

            Case StyleEnum.DoubleZero, StyleEnum.IntegerZero
                MyBase.TextAlign = HorizontalAlignment.Right
                If _min < 0 And _max > 0 Then
                    def = "0"
                Else
                    def = _min.ToString
                End If

        End Select

        If Me.Text = "" Or Me.Text = "0" Or Not Me.validateText Then
            Me.Text = def
        End If
    End Sub


    Private Function validateText() As Boolean
        Dim negativeOk As Boolean = False
        Dim checkDouble As Boolean = False
        Dim checkInteger As Boolean = False
        Dim valueOk As Boolean = False

        Select Case _style
            Case StyleEnum.Double, StyleEnum.DoubleZero
                checkDouble = True

            Case StyleEnum.Integer, StyleEnum.IntegerZero
                checkInteger = True

            Case StyleEnum.TextOnChange, StyleEnum.TextOnValidate
                valueOk = True
        End Select

        If Not valueOk Then
            Dim txt As String = Me.Text
            If String.IsNullOrEmpty(txt) Then
                valueOk = True
            ElseIf _min < 0 And txt = "-" Then
                valueOk = True
            Else
                Dim tmp As Double = 0
                If checkDouble Then
                    valueOk = Double.TryParse(txt, Globalization.NumberStyles.Float, nfi, tmp)
                ElseIf checkInteger Then
                    valueOk = Integer.TryParse(txt, Globalization.NumberStyles.Float, nfi, tmp)
                End If

                If valueOk And ((tmp > _max) Or ((tmp < _min) And (tmp.ToString.Length >= _min.ToString.Length))) Then
                    'if value could be parsed, but
                    'value is too large or
                    'value is too small, even though the length is sufficient (to allow entering incomplete numbers, e.g. "2", if _min=10)
                    'NOTE: too small numbers will be caught in validation event
                    valueOk = False
                End If
            End If
        End If

        Return valueOk
    End Function
#End Region

#Region "Events"
    Private Sub WdTextbox_TextChanged(sender As Object, e As EventArgs) Handles Me.TextChanged
        Dim valueOk As Boolean = Me.validateText

        If Not valueOk Then
            Dim oldPos As Integer = Me.SelectionStart
            Me.Text = _oldText
            If (oldPos > 0) Then
                Me.SelectionStart = oldPos - 1
            End If
        Else
            Me._oldText = Text

            If Me._style = StyleEnum.TextOnChange Then
                RaiseEvent ApplyValue(Me, New System.EventArgs)
            End If
        End If
    End Sub

    Private Sub WdTextbox_Validating(sender As Object, e As CancelEventArgs) Handles Me.Validating
        Dim txt As String = Me.Text
        Dim raise As Boolean
        Select Case _style
            Case StyleEnum.Double, StyleEnum.Integer
                Dim tmp As Double = 0
                If Double.TryParse(txt, Globalization.NumberStyles.Float, nfi, tmp) Then
                    If tmp < _min Then
                        tmp = _min
                    ElseIf tmp > _max Then
                        tmp = _max
                    End If

                    Me.Text = IIf(tmp <> 0, tmp.ToString, "")
                Else
                    Me.Text = ""
                End If
                raise = True

            Case StyleEnum.DoubleZero, StyleEnum.IntegerZero
                Dim tmp As Double = 0
                If Double.TryParse(txt, Globalization.NumberStyles.Float, nfi, tmp) Then
                    If tmp < _min Then
                        tmp = _min
                    ElseIf tmp > _max Then
                        tmp = _max
                    End If

                    Me.Text = tmp.ToString
                Else
                    Me.Text = "0"
                End If
                raise = True

            Case StyleEnum.TextOnChange
                raise = False

            Case StyleEnum.TextOnValidate
                raise = True
        End Select

        If raise Then
            RaiseEvent ApplyValue(Me, New System.EventArgs)
        End If
    End Sub
#End Region

End Class
  • First, add a TextBox. 首先,添加一个TextBox。
  • Second, Change the event from TextChanged to KeyPress . 其次,将事件从TextChanged更改为KeyPress
  • You see it at the upper right of your field codes, then click the small arrow. 您可以在字段代码的右上角看到它,然后单击小箭头。
  • Populate this codes between your TextBox1_KeyPress 在TextBox1_KeyPress之间填充此代码

      If Char.IsDigit(e.KeyChar) = False And Char.IsControl(e.KeyChar) = False Then e.Handled = true MsgBox("Please enter a valid number") End If 
  • I hope it can help you this simple codes 我希望它可以帮助你这个简单的代码
  • for more information http://audzkie.barsalote@gmail.com 了解更多信息,请访问http://audzkie.barsalote@gmail.com

You could use the KeyDown event to check if the value of the key pressed is numeric or '.' 您可以使用KeyDown事件来检查按下的键的值是否为数字或“。” and set the event property handled to true whenever the input is numeric or '.'. 并在输入为数字或“。”时将event属性设置为true。 (I might be wrong with the value of the handled property since i don't remember if it was true or false that discarded the event and hindered the key to be input into the textbox) (我可能错误处理属性的值,因为我不记得丢弃事件是否为真或假,并阻碍了输入到文本框中的键)

Look at the ErrorProvider . 看看ErrorProvider Using that you can prevent focus from leaving control until correct value is entered, at the same time allowing user to press cancel or dialog close buttons. 使用它可以防止焦点离开控制,直到输入正确的值,同时允许用户按取消或对话框关闭按钮。

This works 这有效

Private Sub txt1_PreviewTextInput(sender As Object, e As TextCompositionEventArgs) Handles txt1.PreviewTextInput
   e.Handled = Not IsNumeric(e.Text)
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM