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

时间:2014-12-08 05:58:12

标签: vb.net

尊敬的先生,  我只限制我的文本框中的数字和小数点,我只能通过下面的函数得到数字和小数,但不能限制在输入文本框上出现两次小数点。我猜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

2 个答案:

答案 0 :(得分:1)

您没有注意已经在TextBox中输入的内容,因此您的函数不知道输入了多少小数点。您需要将TextBox的文本传递到您的函数中,或者在发送到您的函数之前预先筛选它。像这样:

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

答案 1 :(得分:0)

尝试这样

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