MaskedTextBox ?

eric13

Active member
Joined
May 25, 2006
Messages
30
Programming Experience
3-5
I have a masked text box with a mask of ####.##

It is being used for a price field. Most of our prices are under $100.00 but some go up over a $1000.00

This is the behavior that i am looking for: if a user types "99" and then the presses "." key, I would like the 99 to be moved next to the masked "." like "99." and then set the cursor to the right of the "."

Currently you type "99" and press "." and it types nothing because of the mask. Seems awkward for the user to have to type 2 spaces and then the "99" and then the cents part of the number to type a price in the text box.

Foxpro uses this behavior as a default when using a numeric field with a mask.

Anyone know a easy way of doing this?
 
The MaskedTextBox controls mask don't support variable optional length masks. (only if caret is placed at appropriate position first is previous blanks skipped)

Here is an alternative using the regular TextBox control, also add an ErrorProvider control to the form.
VB.NET:
    Private Sub TextBox1_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) _
    Handles TextBox1.Validating
        Dim expression As String = "^\d{0,4}(\.\d{0,2})?$"
        If System.Text.RegularExpressions.Regex.Match(TextBox1.Text, expression).Success Then
            ErrorProvider1.SetError(TextBox1, "")
        Else
            e.Cancel = True
            ErrorProvider1.SetError(TextBox1, "Enter number in this format: ####.##")
        End If
    End Sub
This won't display the mask in textbox, only on error. If you want this you can add a default value or a mask as initial text and make all text selected when user enter the textbox (use the Enter event and textbox.SelectAll method).

The regular expression used to validate accept empty text, to require a number you can change the integer part from 0,4 digits to 1,4 digits. Here's the site if you need help with regular expressions. Expression above accept integer part 0-4 digits plus optional decimal part with '.' character as delimiter and 0-2 decimal digits.
 
Back
Top