允许用户只写一个点并且只在文本框VB.NET 2010中编号

时间:2012-10-17 16:18:08

标签: vb.net forms validation

我有一个文本框,我使用以下内容验证用户只能添加数字,但我怎样才能让用户只能写一个“。”

Private Sub txtDiagnostic_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtConsultor.KeyPress
        If e.KeyChar <> ChrW(Keys.Back) Then
            If Char.IsNumber(e.KeyChar) Then
            Else
                e.Handled = True
            End If
        End If
    End Sub

我正在计划使用contains()或其他东西,但我怎么能意识到文本框有 只有一个点?或者如何让用户只能写一个点?

2 个答案:

答案 0 :(得分:2)

在第一个IF

之前添加此行
If (e.KeyChar.ToString = ".") And (txtDiagnostic.Text.Contains(e.KeyChar.ToString)) Then
     e.Handled = True
     Exit Sub
End If

答案 1 :(得分:-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