User Rating: 0 / 5

Star InactiveStar InactiveStar InactiveStar InactiveStar Inactive
 

MaskedTextBox Control [System.Windows.Forms.MaskedTextBox]

Represents an enhanced text box control that supports a declarative syntax for accepting or rejecting user input.

MaskedTextBox in the Toolbox

Default Event: MaskInputRejected

Why use a MaskedTextBox control?

Use the MaskedTextBox to distinguish between proper and improper user input. By using a mask, you can specify the format of the input without custom validation.

 

Important Properties:

Mask

This property sets the string governing the input for this control. 

Why use the Mask property?

Use the Mask property to limit the textbox’s input to a specific format. You can define your own custom mask or preferably select from a predefined set using the designer. The designer has a useful set of predefined masks such as date time formats, phone numbers, and zip codes.

Designer Input Predefined Masks

You can access the predefined mask via the Property Pane:

Edit Mask in Property Pane

Or directly in the designer:

Edit Mask in Designer

If you need to create you own format, please refer to the following table or go to the Mask Property MSDN Help Page for more details.

Mask Element Description
0 Digit, required. This element will accept any single digit between 0 and 9.
9 Digit or space, optional.
# Digit or space, optional. If this position is blank in the mask, it will be rendered as a space in the Text property. Plus (+) and minus (-) signs are allowed.
L Letter, required. Restricts input to the ASCII letters a-z and A-Z. This mask element is equivalent to [a-zA-Z] in regular expressions.
? Letter, optional. Restricts input to the ASCII letters a-z and A-Z. This mask element is equivalent to [a-zA-Z]? in regular expressions.
& Character, required. If the AsciiOnly property is set to true, this element behaves like the “L” element.
C Character, optional. Any non-control character. If the AsciiOnly property is set to true, this element behaves like the “?” element.
A Alphanumeric, required. If the AsciiOnly property is set to true, the only characters it will accept are the ASCII letters a-z and A-Z. This mask element behaves like the “a” element.
a Alphanumeric, optional. If the AsciiOnly property is set to true, the only characters it will accept are the ASCII letters a-z and A-Z. This mask element behaves like the “A” element.
. Decimal placeholder. The actual display character used will be the decimal symbol appropriate to the culture.
, Thousands placeholder. The actual display character used will be the thousands placeholder appropriate to the culture.
: Time separator. The actual display character used will be the time symbol appropriate to the culture.
/ Date separator. The actual display character used will be the date symbol appropriate to culture.
$ Currency symbol. The actual character displayed will be the currency symbol appropriate to the culture.
< Shift down. Converts all characters that follow to lowercase.
> Shift up. Converts all characters that follow to uppercase.
| Disable a previous shift up or shift down.
  Escape. Escapes a mask character, turning it into a literal. “\” is the escape sequence for a backslash.
All other characters Literals. All non-mask elements will appear as themselves within MaskedTextBox. Literals always occupy a static position in the mask at run time, and cannot be moved or deleted by the user.

An example mask for a US phone number is a follows:

(999) 000-0000

In this mask the first three digits are optional and the last seven are required. The parentheses are considered Literals, which means the user cannot altered them.

Resulting MaskedTextBox with Phone Number Mask:
MaskedTextBox using U.S. Phone Mask

 

BeepOnError

This property indicates whether the masked text box control raises the system beep for each user key stroke that it rejects.

Values (Default: $False):

$True/ $False

 

Culture

This property sets the culture information associated with the masked text box.

Set this property if you are specifically targeting a culture that is not the current default (English (United States) for US machines). This effects the format of the date time entries and these changed will be reflected when selecting predefined masks as mentioned above.

 

MaskCompleted

This property indicates whether all required inputs have been entered into the input mask.

The MaskCompleted property can be useful when it comes to validating the data. See the MaskFull property for an example.

 

MaskFull

This property indicates whether all required and optional inputs have been entered into the input mask.

This property is similar to MaskCompleted property with the exception that it also encompasses optional inputs specified in the Mask property. To compare these properties and to demonstrate their usefulness when it comes to validating, we will look at validating a phone number. The predefined Mask for a US phone number specifies that the area code (first three digits) is optional and the remaining seven digits are mandatory.

The following examples will help demonstrate the difference between the two properties:

Partially completed phone number:

Partial Phone Number

Property Value
MaskCompleted False
MaskFull False

 

Phone number without an area code:

Phone number without Area Code

Property Value
MaskCompleted True
MaskFull False

 

Completed phone number:

Completed Phone Number

Property Value
MaskCompleted True
MaskFull True

 

Text

The property gets or sets the text as it is currently displayed to the user. 

The value returned may include formatting characters specified in the Mask property. See the TextMaskFormat property for more information.

 

TextMaskFormat

This property determines whether the string returned by the Text property includes literals and/or prompt characters.

Use the TextMaskFormat if you need to modify the format of the string that is returned by the Text property of the MaskedTextBox control.

Values (Default: IncludeLiterals):

The example values displayed are based on he following MaskTextBox:

Phone number without Area Code

IncludePrompt
Return text input by the user as well as any instances of the prompt character.

Text: “___5555555″

 

IncludeLiterals
Return text input by the user as well as any literal characters defined in the mask.

Text: “(   ) 555-5555″

 

IncludePromptAndLiterals
Return text input by the user as well as any literal characters defined in the mask and any instances of the prompt character.

Text:  “(___) 555-5555″

 

ExcludePromptAndLiterals
Return only text input by the user.

Text: ”   5555555″

 

ValidatingType

This property contains the data type used to verify the data input by the user.

You need not set this property normally, since the preset Masks already set this property appropriately. This ensures data types are within the correct range. For example “77/77/7777” is a valid format for a date, but the value is not.

You must set the ValidatingType property to a type, which in PowerShell is defined by the full class name surrounded by brackets. For example, to set the ValidatingType to a DateTime you will need to do the following:

$maskedtextboxBirthDate.ValidatingType = [System.DateTime]

Again you need not set this property if you are using a predefined mask.

Note: The ValidatingType property looks for a static method named “Parse” that must be present in the Type to validate the content. Since the DateTime class has a Parse method, it is compatible:

[System.DateTime]::Parse()

Other Common Types with the Parse static method includes the all the basic value types, such as:

[Int]

 

[Double]

 

[Float]

All enumerators are compatible, such as:

[System.Windows.Forms.DialogResult]

 

[Microsoft.PowerShell.ExecutionPolicy]

 

Important Methods:

ValidateText

This method converts the user input string to an instance of the validating type.

Use this method to determine if the content of the MaskTextBox is valid. This method requires that a compatible type be set in the ValdiatingType property. If the ValidateText fails it will return a $null value otherwise it will return an object of the corresponding type.

Example:

    if($maskedtextboxBirthDate.ValidatingType -ne $null)
    {
        if($maskedtextboxBirthDate.ValidateText() -eq $null)
        {
            #Validation Failed
        }
        else
        {
            #Validation Successful  
        }
    }

Note: The MaskTextBox will automatically validate the text when it loses focus.

 

Important Events:

MaskInputRejected

This event occurs when the user’s input or assigned character does not match the corresponding format element of the input mask.

Use this event when you want to react to invalid input:

$maskedtextboxPhone_MaskInputRejected=[System.Windows.Forms.MaskInputRejectedEventHandler]{
#Event Argument: $_ = [System.Windows.Forms.MaskInputRejectedEventArgs]    
    $labelError.Text = "Failed input -Postion ({0}): {1}"  -f $_.Position, $_.RejectionHint.ToString()
}

The event passes a parameter variable $_ . Use this variable to access the following properties:

$_.Position

Returns the position in the mask corresponding to the invalid input character.

 

$_.RejectionHint

Returns an enumerated value [System.ComponentModel.MaskedTextResultHint] that describes why the input character was rejected. Please see the MSDN MaskTextResultHist Help page for more information.

 

TypeValidationCompleted

This event occurs when MaskedTextBox has finished parsing the current value using the ValidatingType property.

Use this event in order to react to when a type validation fails or succeeds. This event is also fired when the ValdiateText method is called.

$maskedtextboxBirthDate_TypeValidationCompleted=[System.Windows.Forms.TypeValidationEventHandler]{
#Event Argument: $_ = [System.Windows.Forms.TypeValidationEventArgs]
    if($_.IsValidInput -eq $false)
    {
        $_.Cancel = $true #Keep the focus on the control
        $errorprovider1.SetError($maskedtextboxBirthDate, "Invalid Date Format");
    }
    else
    {
        $errorprovider1.SetError($maskedtextboxBirthDate, "");    
    }
}

The TypeValdiationCompleted passes a parameter variable $_. The following are important properties you can access with this variable:

$_.Cancel

This property indicates whether the event should be canceled. Set it to $true to retain the focus on the MaskTextBox.

 

$_.IsValidInput

This property indicates whether the formatted input string was successfully converted to the validating type.

 

$_.ReturnValue

This property returns the object that results from the conversion of the formatted input string.

For an example use of the MaskTextBox, please refer to the samples used in Validating the Form.

If you have questions about our products, please post in our support forum.
For licensed customers, use the forum associated with your product in our Product Support Forums for Registered Customers.
For users of trial versions, please post in our Trial Software Questions forum.
Copyright © 2017 SAPIEN Technologies, Inc.