简体   繁体   English

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

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

Repected Sir, I am restricting my textbox for numbers and decimal points only, i am able to get numbers and decimals only by the below function but not able to restrict making decimal points appearing twice on the input textbox. 尊敬的先生,我仅限制数字和小数点为文本框,只能通过以下功能获取数字和小数,但不能限制使小数点在输入文本框上出现两次。 I guess If singleChars.IndexOf(KeyChar) > 0 And (Asc(KeyChar)) <> 8 has some errors and if its wrong how to solve it ? 我想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

And my public function from class file is 我从类文件的公共功能是

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

Yours faithfully Murulimadhav 您忠实的Murulimadhav

You are not paying attention to what has already been entered in your TextBox, therefore your function has no idea how many decimals points have been entered. 您无需注意已在TextBox中输入的内容,因此您的函数不知道已输入了多少个小数点。 You need to either pass the TextBox's Text into your function or prescreen it before sending to your function. 您需要将TextBox的Text传递到函数中,或在发送给函数之前对其进行预筛选。 Something like this: 像这样:

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

Try Like this 像这样尝试

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