在VB.NET中,如何让文本框只允许一个小数点,<之前3NUMBERS,之后只有1NUMBER?

时间:2015-06-18 15:19:56

标签: asp.net vb.net

正如问题所示,我需要一个文本框,只允许一个小数点,前面少于三个数字,后面只有一个数字。

到目前为止,我已经编译了这段代码。

Private Sub TextBox14_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox14.KeyPress
    Dim keyChar = e.KeyChar

    If Char.IsControl(keyChar) Then
        'Allow all control characters.
    ElseIf Char.IsDigit(keyChar) OrElse keyChar = "."c Then
        Dim text = Me.TextBox14.Text
        Dim selectionStart = Me.TextBox14.SelectionStart
        Dim selectionLength = Me.TextBox14.SelectionLength

        text = text.Substring(0, selectionStart) & keyChar & text.Substring(selectionStart + selectionLength)

        If Integer.TryParse(text, New Integer) AndAlso text.Length > 3 Then
            'Reject an integer that is longer than 16 digits.
            e.Handled = True
        ElseIf Double.TryParse(text, New Double) AndAlso text.IndexOf("."c) < text.Length - 3 Then
            'Reject a real number with two many decimal places.
            e.Handled = True
        End If
    Else
        'Reject all other characters.
        e.Handled = True
    End If
End Sub

我得到的最大问题是用户可以输入多个小数点,然后基本上我创建的所有规则都会消失。此外,当我需要时,用户无法在小数点前设置2个数字。

1 个答案:

答案 0 :(得分:0)

用我的头解决了它。

Private Sub TextBox11_KeyPress(ByVal sender As Object,ByVal e As System.Windows.Forms.KeyPressEventArgs)处理TextBox11.KeyPress         &#39;允许在销售价格文本框中输入什么内容         Dim keyChar = e.KeyChar

    If Char.IsControl(keyChar) Then
        'Allow all control characters.
    ElseIf Char.IsDigit(keyChar) OrElse keyChar = "."c Then
        Dim text = Me.TextBox11.Text
        Dim selectionStart = Me.TextBox11.SelectionStart
        Dim selectionLength = Me.TextBox11.SelectionLength

        text = text.Substring(0, selectionStart) & keyChar & text.Substring(selectionStart + selectionLength)
        If TextBox11.Text.Contains("."c) Then
            'Forbids a user from entering in two decimal places
            If keyChar = "."c Then
                e.Handled = True
            ElseIf text.Length - text.IndexOf("."c) > 3 Then
                e.Handled = True
            End If
        Else 'no decimal point currently in textbox
            If text.Length > 5 And keyChar = ("."c) Then 'Allows only a "." to be written 
                e.Handled = False
            ElseIf text.Length > 5 Then ' Numbers before decimal point above 99,999
                e.Handled = True
            End If
        End If
    Else
        'Reject all other characters for this textbox.
        e.Handled = True
    End If
End Sub