Open In App

How to Mask input in MaskedTextBox in C#?

In C#, MaskedTextBox control gives a validation procedure for the user input on the form like date, phone numbers, etc. Or in other words, it is used to provide a mask which differentiates between proper and improper user input. In MaskedTextBox control, you can mask the input of the MaskedTextBox using Mask Property which will be used at runtime to enter some specific type of input in the box.
For example, if you want to enter the phone number in the MaskedTextBox, then you will use the mask property. This property converts the input in the phone number format. It is the default property of MaskedTextBox and if you try to change the mask when the MaskedTextBox already masked with the previous mask. So, it will relocate that input according to the new mask and if it fails in relocation, then it will clear the existing input from the MaskedTextBox. The default value of this property is an empty string, means it can contain any string. You can set this property in two different ways:

1. Design-Time: It is the easiest way to set the Mask property of the MaskedTextBox as shown in the following steps:



2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the Mask property of the MaskedTextBox control programmatically with the help of given syntax:

public string Mask { get; set; }

Here, the string indicates the current mask. If the string applied to this property does not belong to a valid mask, then it will throw an InvalidEnumArgumentException. The following steps show how to set the Mask property of the MaskedTextBox dynamically:


Article Tags :
C#