fh09asdfha89sdf
fh09asdfha89sdf

Reputation: 1

Manipulating E.Handled code (VB.NET)

I currently have this E-handled code which will allow a user to type in 5 numbers, then a decimal point, then 2 more numbers:

Private Sub txtbox11_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtbox11.KeyPress 'What is allowed to be typed in sale price 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

The problem is, if someone completes the entry, then clicks before the decimal point, they can write in an infinite amount of numbers. What creative code bypass can you think of that would prevent this?

Upvotes: 0

Views: 296

Answers (1)

Paul Ishak
Paul Ishak

Reputation: 1093

Actually, your best bet is probably going to be to use a maskedtextbox with a mask of $#####.##

ex:

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

Upvotes: 0

Related Questions