繁体   English   中英

VB.Net VS 2008验证textbox.text仅保留一个小数点

[英]VB.Net VS 2008 validating textbox.text for one decimal point only

尊敬的先生,我仅限制数字和小数点为文本框,只能通过以下功能获取数字和小数,但不能限制使小数点在输入文本框上出现两次。 我想If singleChars.IndexOf(KeyChar) > 0 And (Asc(KeyChar)) <> 8有一些错误,如果错误,该如何解决?

Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
        e.Handled = myClasses.onlyCurrency(e.KeyChar)
    End Sub

我从类文件的公共功能是

Public Shared Function onlyCurrency(ByVal KeyChar As Char) As Boolean
        Dim allowedChars As String
        allowedChars = "0123456789."
        Dim singleChars As String
        singleChars = "."
        If allowedChars.IndexOf(KeyChar) = -1 And (Asc(KeyChar)) <> 8 Then
            Return True
        End If
        If singleChars.IndexOf(KeyChar) > 0 And (Asc(KeyChar)) <> 8 Then
            Return True
        End If
        Return False
    End Function

您忠实的Murulimadhav

您无需注意已在TextBox中输入的内容,因此您的函数不知道已输入了多少个小数点。 您需要将TextBox的Text传递到函数中,或在发送给函数之前对其进行预筛选。 像这样:

Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress
    e.Handled = myClasses.onlyCurrency(e.KeyChar, CType(sender, TextBox).Text)

End Sub



Public Shared Function onlyCurrency(ByVal KeyChar As Char, CurrentText As String) As Boolean
    Dim allowedChars As String
    allowedChars = "0123456789."
    Dim singleChars As String
    singleChars = "."
    If KeyChar = singleChars Then
        If CurrentText.Contains(singleChars) Then
            Return True
        End If
    End If
    If allowedChars.IndexOf(KeyChar) = -1 And (Asc(KeyChar)) <> 8 Then
        Return True
    End If
    Return False
End Function

像这样尝试

Private Sub TextBox1_KeyPress(ByVal sender As System.Object, ByVal e As 
System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress

    If Char.IsDigit(e.KeyChar) = False AndAlso e.KeyChar <> "." Then
        e.Handled = True
    ElseIf e.KeyChar = "." AndAlso TextBox1.Text.Trim.Contains(".") Then
        e.Handled = True
    Else
        e.Handled = False
    End If

End Sub

暂无
暂无

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

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