User Interface / Widgets / Text / Masked Text Box
In This Topic
    Masked Text Box
    In This Topic

    The masked text box is a text box that uses a mask to distinguish between proper and improper user input. The mask is controlled through the Mask property and can contain the following characters:

    Mask Character 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.
    C Character, optional.
    A Alphanumeric, required.
    a Alphanumeric, optional.
    . Decimal placeholder. The actual display character used will be the decimal symbol appropriate to the format provider, as determined by the control's FormatProvider property.
    , Thousands placeholder. The actual display character used will be the thousands placeholder appropriate to the format provider, as determined by the control's FormatProvider property.
    All other characters Literals. All non-mask elements will appear as themselves within NMaskedTextBox. Literals always occupy a static position in the mask at run time, and cannot be moved or deleted by the user.

    When a mask is set to the text box, the text of the text box is initialized based on that mask by replacing the special characters above with the PromptChar of the masked text box. It is by default set to underscore ('_').

    When a character entered by the user is rejected by the masked text box, the MaskInputRejected event is fired. This event's argument contains information about the rejected character and the reason it was rejected for in its Character and Reason properties respectively.

    The following piece of code demonstrates how to create a masked text box that accepts credit card numbers:

    Creating and using a masked text box
    Copy Code
    creditCardNumberTextBox = new NMaskedTextBox();
    creditCardNumberTextBox.Mask = "0000 0000 0000 0000";
    creditCardNumberTextBox.MaskInputRejected += OnMaskInputRejected;
    
    private void OnMaskInputRejected(NMaskInputRejectedEventArgs arg)
    {
        NTrace.Writeline("Rejected Character: '" + arg.Character + "', reason: '" +
            NStringHelpers.InsertSpacesBeforeUppersAndDigits(arg.Reason.ToString()) + "'");
    }
    
    See Also