操纵E.Handled代码(VB.NET)

时间:2015-06-23 13:35:45

标签: vb.net

我目前有这个电子处理代码,允许用户键入5个数字,然后是小数点,然后再输入2个数字:

Private Sub txtbox11_KeyPress(ByVal sender As Object,ByVal e As System.Windows.Forms.KeyPressEventArgs)处理txtbox11.KeyPress         '允许在销售价格txtbox中输入什么         Dim keyChar = e.KeyChar

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

        text = text.Substring(0, selectionStart) & keyChar & text.Substring(selectionStart + selectionLength)
        If txtbox11.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 txtbox
            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 txtbox.
        e.Handled = True
    End If
End Sub

问题是,如果有人完成输入,然后在小数点前点击,他们可以写入无限数量的数字。你能想到什么创意代码绕过会阻止这种情况?

1 个答案:

答案 0 :(得分:0)

实际上,你最好的选择可能是使用掩码为$ #####的maskedtextbox。##

例如:

Option Strict On
Option Explicit On
Option Infer Off
Public Class Form1
    Friend WithEvents MaskedTextBox1 As New MaskedTextBox With {.Parent = Me, .Font = New Font("Consolas", 8)}
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        MaskedTextBox1.Mask = "$#####.##"
        MaskedTextBox1.PromptChar = " "c 'Delete this line if you want underscores
    End Sub
End Class