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

如何允许用户在vb.net的文本框中只输入数字?,vb.net,Vb.net,如何防止用户在vb.net 2005的文本框中输入字符,而只输入数字和“.”?您可以使用KeyDown事件检查按键的值是否为数字或“.”,并在输入为数字或“.”时将处理的事件属性设置为true。(我可能对handled属性的值有错误,因为我不记得丢弃事件并阻止将键输入文本框的是真是假)只是为了帮助,我为计算器制作了一个片段,它可能会有帮助,它允许删除、退格、数字和“.”字符。还可以添加对函数的调用,以在按Enter键时处理文本框 Private Sub Box_Input_KeyDown(B

如何防止用户在vb.net 2005的文本框中输入字符,而只输入数字和“.”?

您可以使用KeyDown事件检查按键的值是否为数字或“.”,并在输入为数字或“.”时将处理的事件属性设置为true。(我可能对handled属性的值有错误,因为我不记得丢弃事件并阻止将键输入文本框的是真是假)

只是为了帮助,我为计算器制作了一个片段,它可能会有帮助,它允许删除、退格、数字和“.”字符。还可以添加对函数的调用,以在按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

此代码允许输入所有数字、空格和删除键,并且文本中只允许一个“.”。一个想法可能是添加TAB函数以允许TAB停止。

以下内容将允许您测试特定的键值(从):

Private Sub TextBox1\u KeyPress(ByVal sender作为对象,ByVal e作为System.Windows.Forms.KeyPressEventArgs)处理TextBox1.KeyPress
If(Microsoft.VisualBasic.Asc(e.KeyChar)<48)_
或者(Microsoft.VisualBasic.Asc(e.KeyChar)>57)然后
e、 已处理=真
如果结束
如果(Microsoft.VisualBasic.Asc(e.KeyChar)=8),则
e、 已处理=错误
如果结束
端接头
如果这不是您要查找的,请尝试使用
isNumeric()
函数。

查看。使用该选项可以防止焦点在输入正确的值之前离开控件,同时允许用户按“取消”或“对话框关闭”按钮

Dim num1 As Integer

Try   

   num1 = Cint(TextBox1.Text)

Catch ex As Exception

   TextBox1.Clear()    
   TextBox1.Focus()

End Try
对于单个数字,您可以使用
num1=Csng(textbox1.text)

尝试以下方法:

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
但这只允许数字,并且您可以在添加此条件时允许十进制数字:

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

另一个简单的选择是:

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

我编写了一个傻瓜证明例程,它消除了字母字符,并允许所有其他字符

从技术上讲,您可以在字符串中放入任何想要的字符,以防止它像标点符号一样被输入

    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

这是一种非常简单的方法,可以防止在您选择的任何文本框或字段中输入disallowedKeys字符串中的任何字符,只需让控件的KeyDown事件引用此方法即可

在我看来,以下是更好的答案:

   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

干杯,Sach

在stackoverflow和其他地方搜索了一些结果后,我对我找到的解决方案不满意:它们都有一些缺点,主要是键盘布局问题或控制键的错误处理,例如Ctrl+C不再可能

我尝试过的解决方案都是向下键/向上键的方法;我决定尝试TextChanged事件并实现简单的逻辑:如果当前输入没有验证,那么用旧值替换它;否则:更新旧值

当然,和往常一样,实现特性细节变得有点复杂:o |…但最终我有了一个文本框,可以限制为指定范围内的整数值或双数值,并有一个新事件ApplyValue,可以监听,而不是文本更改或验证,这取决于所选的样式,即数字值在键入时不应触发事件,但对于某些文本值可能是可取的

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
导入System.ComponentModel
公共类受限文本框
继承Windows.Forms.TextBox
#区域“构造函数、样式枚举、ApplyValue事件”
公共分新()
MyBase.New()
端接头
'由于创建UiTypeEditor的开销,请使用枚举而不是标志
公共枚举样式枚举
[整数]
整数零
[双份]
双零
文本更改
文本验证
结束枚举
公共事件ApplyValue(发送方作为对象,e作为System.EventArgs)
#末端区域
#地区“新物业”
私有_样式为StyleEnum=StyleEnum.TextOnValidate
_
公共阴影属性样式作为StyleEnum
得到
返回式
结束
设置(值为StyleEnum)
_风格=价值
initializeText()
端集
端属性
Private _min作为整数=0
_
公共属性最小值为整数
得到
返回_min
结束
设置(值为整数)
_最小值=值
initializeText()
端集
端属性
Private _maxas Integer=2147483647
_
公共属性最大值为整数
得到
返回最大值
结束
设置(值为整数)
_最大值=最大值
initializeText()
端集
端属性
#末端区域
#区域“阴影属性”
'隐藏并不允许更改
_
公共阴影属性TextAlign As Windows.Forms.HorizontalAlignment
得到
返回MyBase.TextAlign
结束
设置(值为Windows.Forms.HorizontalAlignment)
“什么也不做
端集
端属性
“隐藏并始终使用false
_
公共阴影属性多行为布尔值
得到
返回错误
结束
设置(值为布尔值)
MyBase.Multiline=False
端集
端属性
“隐藏并始终使用true
_
公共阴影属性导致验证为布尔值
得到
返回真值
结束
设置(值为布尔值)
MyBase.CausesValidation=True
端集
端属性
'隐藏,但模拟默认值
_
公共阴影建筑红线作为字符串()
得到
返回MyBase.line
结束
设置(值为String())
   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
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
 Dim Validinputchar = "0123456789." + vbBack

    If Not Validinputchar.Contains(e.KeyChar) Then

        e.KeyChar = Nothing

    End If
 If Char.IsDigit(e.KeyChar) = False And Char.IsControl(e.KeyChar) = False Then
               e.Handled = true
               MsgBox("Please enter a valid number")
 End If
Private Sub txt1_PreviewTextInput(sender As Object, e As TextCompositionEventArgs) Handles txt1.PreviewTextInput
   e.Handled = Not IsNumeric(e.Text)
End Sub