Visual C#

Windows Control: Masked Text Box

The regular text box, also referred to as the edit control in Microsoft Windows (Win32), allows the user to enter any type of string in the control. As we…

6 min read1,263 words

Introduction#

A standard text box, often called an edit control in Win32, permits users to input any string. As previously discussed, it can be transformed into a multi-line memo, similar to a Notepad application. However, there are scenarios where stricter input control is required, such as ensuring a date field doesn't receive a name, or a phone number field doesn't get a salary figure. To facilitate precise data entry, the .NET Framework provides the masked text box. This control uses placeholders to enforce character rules—accepting specific types, rejecting others, and displaying fixed characters that cannot be deleted—while keeping the original behavior intact.

Creating a Masked Text Box#

To create a masked text box, from the Common Controls section of the Toolbox, you can more readily click MaskedTextBox and click the form. To programmatically create a masked text box, declare a variable of type MaskedTextBox, use the New operator to initialize it, and add it to the Controls collection of its container. The masked text box uses the same common characteristics of other visual control: location, size, etc while keeping the original behavior intact.

Characteristics of the Masked Text Box#

Introduction#

The masked text box uses the same common characteristics of other visual control: name, location, size, background color, border size, anchoring, docking, font, etc. Like the regular text box, the MaskedTextBox class is derived from TextBoxBase that provides its fundamental properties. This means that with the masked text box, you can cut or copy text from it, you can paste text to it, you can measure the length of its text, you can select some part of its text from a specific position to another, or you can select all of its text. Like the regular text box, the masked text box uses the AsciiOnly property, which indicates whether the control should accept or allow only ASCII characters. The primary reason for using a masked text box is to control short lengths of text entered into it. For this reason, you should not consider some of the multi-line characteristics of a regular text box: word wrapping, scroll bars, the ability to use the Tab key inside the control, etc.

The Mask#

Probably the most important property of a masked text box, which sets it apart from the (traditional) text box control, is its ability to control what the user can and cannot enter in the text side. To visually configure this text, the MaskedTextBox class is equipped with a property named Mask. There are two main ways you can configure it:

  • If you already know the mask you want to use, access the Properties window for the control and, in the Mask field, type the right formula
  • If you do not know or are not sure, in the Properties window for the control Click Mask and click its ellipsis button On the form, click the control and, under the Properties window, click Set Mask... On the form, click the control, click the arrow button on it, and click Edit Mask...

Any of these actions would open the Input Mask dialog box:

The Input Mask dialog box offers common masks for Windows and database use, with options varying based on the computer's language settings (e.g., US English for Social Security Numbers and phone formats). You can select an existing mask or create a custom one by clicking <Custom> or editing the Mask field in the Properties window. Masks are built using specific characters: '0' for a mandatory digit, '9' for an optional digit or space, and '#' for an optional digit or sign. 'L' requires a letter, '?' allows an optional letter, and '&' or 'C' allow any character (with '&' following '?' rules if AsciiOnly is True). 'A' or 'a' allow letters and digits. Use '>' to convert to uppercase and '<' for lowercase, with '|' to stop conversion. Special symbols like '.', ',', ':', '/', and '$' are used for decimals, separators, time, dates, and currency, while '\' is for escape sequences. Programmatic masks are set via the Mask property string.

The Placeholder Character#

When you create a mask, to indicate a placeholder for a letter, a digit, or a symbol, the control uses a specific character. The default character is the underscore. If you want, you can use a different character. To support this, the MaskedTextBox class is equipped with the PromptChar property. To change it visually, access the Properties window for the control, click PromptChar and type the desired character. To programmatically specify the character of the placeholders, assign a string to the PromptChar property.

Entering the Wrong Character#

When using the control, the user must must know the rules to follow based on the mask in the control: dates, telephone numbers, etc. The user must also enter only the allowed characters. If the user enters an invalid character, you can make the computer produce a sound (a beep). To assist you with this, the MaskedTextBox is equipped with a Boolean property named BeepOnError. When this property is set to True, if the user enters an invalid character, the computer produces the beep sound. Also, if the user enters an invalid character in the control, the control fires a MaskInputRejected event. You can (continuously) use this event to find out whenever the user enters a wrong character so you can assist the user.

Allowing the Placeholder Character for Input#

After creating the control, you can then use it in your application. When the control comes up, it usually shows its placeholders using a specific character. The most regularly used character is the underscore. Put in reverse, the presence of the underscore indicates a placeholder. If you skip a placeholder by pressing the Space bar, an underscore displays in the space you left. This rule also apples for all other characters we reviewed. In some cases, you may want to formally use the character in the placeholder. To illustrate this, consider that you have applied a mask as &&&&&&. When the control comes up, if Fe_ GT4, this would be considered as Fe GT4 (with an empty space where the _ was typed). In some cases, you may want the user to be able to enter the character of the placeholder so that Fe_ GT4 would produce Fe_ GT4. To assist you with this, the MaskedTextBox class is equipped with the AllowPromptAsInput Boolean property.

Hiding the Placeholder When Focus is Lost#

By default, when the control comes up, it uses some characters, such as _, to show its placeholder(s). This allows the user to know where a character is expected and the number of characters that are expected. After the user has used the control and pressed Tab or clicked another control, the masked text box may still show its placeholders. If you want, you can hide the placeholders when the control looses focus. To assist you with this, the MaskedTextBox class is equipped with a Boolean property named HidePromptOnLeave. The default value of this property is False, which indicates that the control would always show its placeholder(s). Otherwise, you can set this property to true to hide the placeholder character when the control loses focus.

Keeping the Format on Cut and Copy#

In some instances, users may enter fewer characters than there are placeholders, but they cannot exceed the limit. Derived from TextBoxBase, the masked text box includes a context menu for cut, copy, and paste operations. You can determine whether mask characters are included in these actions using the CutCopyMaskFormat property, which utilizes members of the MaskFormat enumeration: ExcludePromptAndLiterals, IncludeLiterals, IncludePrompt, and IncludePromptAndLiterals. Home Copyright © 2008 C# Key