如何在文本框中只允许数字和点?

问题描述 投票:0回答:14

我想知道如何让我的文本框只接受数字和点,例如:

123.45 或 115 或218.16978

等等

我已经有以下代码:

Private Sub TxtHStof_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TxtHStof.KeyPress
    e.Handled = Not Char.IsDigit(e.KeyChar)
    
End Sub

但这只允许不带点的数字。

我怎样才能更改代码,以便它也允许点,但没有其他?

vb.net textbox
14个回答
12
投票
e.Handled = Not (Char.IsDigit(e.KeyChar) OR e.KeyChar=".")

7
投票

接受的解决方案不适合

  1. 多输入小数,例如“12....1234”
  2. 操作系统特定的小数分隔符

这对我有用

Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress
    Dim DecimalSeparator As String = Application.CurrentCulture.NumberFormat.NumberDecimalSeparator
    e.Handled = Not (Char.IsDigit(e.KeyChar) Or
                     Asc(e.KeyChar) = 8 Or
                     (e.KeyChar = DecimalSeparator And sender.Text.IndexOf(DecimalSeparator) = -1))
End Sub

3
投票

您应该使用

MaskedTextBox
- 请参阅此处了解如何设置格式字符串(它允许您仅限于数字和小数点)

http://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox.mask.aspx


2
投票

通过此代码,您可以使用“,”(欧洲)和“.” (美国)小数。

Private Sub TGewicht_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TGewicht.KeyPress
    e.Handled = Not (Char.IsDigit(e.KeyChar) Or Asc(e.KeyChar) = 8 Or ((e.KeyChar = "." Or e.KeyChar = ",") And (sender.Text.IndexOf(".") = -1 And sender.Text.IndexOf(",") = -1)))
End Sub

2
投票
    '****To Allow only Numbers with Decimal and BACKSPACE enabled****
    If Not (Char.IsDigit(e.KeyChar) Or e.KeyChar = ".") And Not Char.IsControl(e.KeyChar) Then
        e.Handled = True
    End If

1
投票

来自 C# 而不是 VB,我正在尝试这个,但这可行吗:

e.Handled = Not (Char.IsDigit(e.KeyChar) AndAlso e.KeyChar.Equals('.'))

1
投票

在 MODULE o FORM 中插入功能

Public Sub OnlyNumber(Ct As TextBox, MaxLength As Integer)
    Ct.MaxLength = MaxLength
    AddHandler Ct.KeyPress, AddressOf ValidarTeclaNumeros
End Sub

Private Sub ValidarTeclaNumeros(sender As Object, e As KeyPressEventArgs)
    Dim Ct As TextBox
    Ct = sender
    If [Char].IsDigit(e.KeyChar) OrElse [Char].IsControl(e.KeyChar) Then
        'ok 
        'e.Handled = True
    ElseIf [Char].IsPunctuation(e.KeyChar) Then
        If (Ct.Text.Contains(",") OrElse Ct.Text.Contains(".")) Then
            e.Handled = True
        End If


    Else
        e.Handled = True
    End If


End Sub

在加载表单中,仅为您的控件添加此代码(仅包含一个逗号或文档)

OnlyNumber(txtControl, 10)

1
投票

我参加聚会迟到了,但这是我的代码

  Private Sub LoanFeeTextBox_KeyPress(sender As Object, e As KeyPressEventArgs) Handles LoanFeeTextBox.KeyPress
        If Char.IsControl(e.KeyChar) Then
        ElseIf Char.IsDigit(e.KeyChar) OrElse e.KeyChar = "."c Then
            If LoanFeeTextBox.TextLength = 12 And LoanFeeTextBox.Text.Contains(".") = False Then
                LoanFeeTextBox.AppendText(".")
            ElseIf e.KeyChar = "." And LoanFeeTextBox.Text.IndexOf(".") <> -1 Then
                e.Handled = True
            ElseIf Char.IsDigit(e.KeyChar) Then
                If LoanFeeTextBox.Text.IndexOf(".") <> -1 Then
                    If LoanFeeTextBox.Text.Length >= LoanFeeTextBox.Text.IndexOf(".") + 3 Then
                        e.Handled = True
                    End If
                End If
            End If

        Else
            e.Handled = True
        End If
    End Sub

1
投票

我从几乎相同的问题开始,但我确实关心是否能够粘贴。在网上搜索如何执行此操作时,我发现我确实应该处理:

  1. 句点或逗号作为小数点指示符,具体取决于操作系统的设置方式。
  2. 仅允许符合模式的按键,同时仍然允许光标控制字符,如箭头和退格键。
  3. 仅允许粘贴到符合模式的文本框中。我选择的方式是,在粘贴时,代码将粘贴的文本视为正在键入的文本,因此将“a1b.c2d,e3f.g4h,i5j”粘贴到文本框中将显示为“1.2345” " 如果句点是您的小数点指示符,则 "12,345" 如果逗号是您的小数点指示符。

我尝试了 MaskedTextBox,但真的不喜欢它,因为它强制了小数点位置,我真的只是想能够自由填写任何数字。我可能有点过分使用正则表达式进行模式匹配,但现在我应该能够在几乎任何地方重用此代码。

Public Class frmMain

    Dim RegexValidator As System.Text.RegularExpressions.Regex
    Dim FormLoaded As Boolean = False

    Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim RegexDecimalPattern As String = Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator
        RegexDecimalPattern = IIf(RegexDecimalPattern = ".", "\.", RegexDecimalPattern)
        RegexValidator = New System.Text.RegularExpressions.Regex("^\d*" & RegexDecimalPattern & "?\d*$", System.Text.RegularExpressions.RegexOptions.IgnoreCase)
        FormLoaded = True
    End Sub

    Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
        ' Code below is based on
        ' http://www.vbforums.com/showthread.php?626378-how-to-validate-textbox-allows-only-numeric-and-decimal-in-vb-net
        ' but was modified to be based on Regex patterns.
        '
        ' Note that:
        ' KeyPress event validation covers data entry as it is being typed.
        ' TextChanged event validation covers data entry by cut/pasting.
        If Char.IsControl(e.KeyChar) Then
            'Allow all control characters.
        Else
            Dim Text = Me.TextBox1.Text
            Dim SelectionStart = Me.TextBox1.SelectionStart
            Dim SelectionLength = Me.TextBox1.SelectionLength
            Text = Text.Substring(0, SelectionStart) & e.KeyChar & Text.Substring(SelectionStart + SelectionLength)
            If Not RegexValidator.IsMatch(Text) Then e.Handled = True
        End If
    End Sub

    Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
        ' If default text is used in a textbox, a TextChanged event occurs before 
        ' RegexValidator is initialized during the Form Load, so we need to check. 
        If FormLoaded Then
            ' Note that:
            ' KeyPress event validation covers data entry as it is being typed.
            ' TextChanged event validation covers data entry by cut/pasting.
            Dim Text = Me.TextBox1.Text
            Dim ValidatedText As String = ""
            Dim KeyChar As Char
            For Each KeyChar In Text
                If RegexValidator.IsMatch(ValidatedText + KeyChar) Then ValidatedText += KeyChar
            Next
            If (ValidatedText.Length > 0) And (TextBox1.Text <> ValidatedText) Then
                Me.TextBox1.Text = ValidatedText
                Me.TextBox1.SelectionStart += ValidatedText.Length
            End If
        End If
    End Sub
End Class

0
投票
Private Sub TextBox2_KeyPress(
   ByVal sender As Object,
   ByVal e As System.Windows.Forms.KeyPressEventArgs
) Handles TextBox2.KeyPress

    e.Handled = Not (Char.IsDigit(e.KeyChar) Or e.KeyChar = "." Or Asc(e.KeyChar) = 8)
End Sub

0
投票

只需添加另一个解决方案。 此代码限制用户只能输入一个“.”。小数点,仅小数点后两位,可以设置要使用多少位(目前我将其设置为仅允许小数点前最多 5 个整数。还允许使用退格键和删除键。这样它们就可以了)不能多加一个“.”并最终得到“45.5.5”之类的东西。

If Char.IsControl(e.KeyChar) Then
        ElseIf Char.IsDigit(e.keyChar) OrElse e.keyChar = "."c Then


            If Amount_FundedTextBox.TextLength = 5 And Amount_FundedTextBox.Text.Contains(".") = False Then
                Amount_FundedTextBox.AppendText(".")
            ElseIf e.KeyChar = "." And Amount_FundedTextBox.Text.IndexOf(".") <> -1 Then
                e.Handled = True
            ElseIf Char.IsDigit(e.KeyChar) Then
                If Amount_FundedTextBox.Text.IndexOf(".") <> -1 Then
                        If Amount_FundedTextBox.Text.Length >= Amount_FundedTextBox.Text.IndexOf(".") + 3 Then
                            e.Handled = True
                        End If
                    End If
                End If

            Else
                e.Handled = True
        End If

0
投票

您可以通过添加“KeyPress”处理程序(来自 TextBox 属性)并指定允许的字符来限制文本框中的字符输入。 如果该角色被“处理”,则不允许。

Private Sub TextBox_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox.KeyPress
    Dim txt As TextBox = CType(sender, TextBox)

    If Not ((Char.IsDigit(e.KeyChar)) Or (e.KeyChar = "E") Or (e.KeyChar = "e") Or (e.KeyChar = "-")) Then e.Handled = True
    If e.KeyChar = Chr(8) Then e.Handled = False 'allow Backspace
    If e.KeyChar = "." And txt.Text.IndexOf(".") = -1 Then e.Handled = False 'allow single decimal point
    If e.KeyChar = Chr(13) Then GetNextControl(txt, True).Focus() 'Enter key moves to next control
End Sub

0
投票
Private Sub TextBox4_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox4.KeyPress

        ' its worked for only number with point and worked backspace 
        If Not Char.IsDigit(e.KeyChar) And Not e.KeyChar = "." Then
            e.Handled = True
        End If
        If e.KeyChar = "." And TextBox4.Text.IndexOf(".") <> -1 Then
            e.Handled = True
        End If
        If e.KeyChar = "." Then
            e.Handled = False
        End If
        If e.KeyChar = Chr(Keys.Back) Then
            e.Handled = False
        End If
        If Char.IsDigit(e.KeyChar) Then
            If TextBox4.Text.IndexOf(".") <> -1 Then
                If TextBox4.Text.Length >= TextBox4.Text.IndexOf(".") + 3 Then  'replace 2 for greater numbers after decimal point
                    e.Handled = True
                    TextBox4.Focus()
                End If
            End If
        End If
        ' is for only digit with back space 
        e.Handled = Not Char.IsDigit(e.KeyChar)

        If e.KeyChar = Chr(Keys.Back) Then
            e.Handled = False
        End If
        If Char.IsDigit(e.KeyChar) Then
            If TextBox4.Text.IndexOf(".") <> -1 Then
                If TextBox4.Text.Length >= TextBox4.Text.IndexOf(".") + 3 Then  'replace 2 for greater numbers after decimal point
                    e.Handled = True
                    TextBox4.Focus()
                End If
            End If
        End If
    End Sub

-1
投票
Dim e As System.Windows.Forms.KeyPressEventArgs

    If Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57 Then
        e.Handled = True
    Else
        e.Handled = False
    End If
© www.soinside.com 2019 - 2024. All rights reserved.