In this article I will provide a short tutorial, how to use MaskedTextBox in Windows Forms (WinForms) Application using C# and VB.Net.
 
 

What is MaskedTextBox?

The MaskedTextBox is basically a validation control which is used for custom validation.
In case of MaskedTextBox, validation is called as masking where different mask is assigned to the MaskedTextBox.
 
 

Using MaskedTextBox in C# and VB.Net

Form Design

The Form consists of following control:
MaskedTextBox – For Masking in TextBox.
Note: Masking means differentiating between proper and improper user input.
 
Using MaskedTextBox in C# and VB.Net
 
The MaskedTextBox has been assigned with the following properties:

Properties

Mask – For defining different mask or condition of user input that will be acceptable.
Using MaskedTextBox in C# and VB.Net
 

Input Mask

Here you can define the Masking.
In the MaskedTextBox, Masking is of two types i.e. Predefined and Custom.
Using MaskedTextBox in C# and VB.Net
 
The above property can be set through Code-Behind in following way:
Here I am assigning property inside the Form_Load event handler but it can be used in other event handlers i.e. Click, CheckedChanged also based on the requirement.
C#
private void Form1_Load(object sender, EventArgs e)
{
     maskedTextBox1.Mask = "00000";//Allows only 5 Digit number without decimal
     maskedTextBox1.Mask = "AAAAA";//Allows only 5 letters
     maskedTextBox1.Mask = "00/00/0000";//Numbers in Date Format
     maskedTextBox1.Mask = "0,00,000";//Allows 6 Digit number with comma
     maskedTextBox1.Mask = "00:00";//Numbers in Time Format
}
 
VB.Net
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
     maskedTextBox1.Mask = "00000" 'Allows only 5 Digit number without Decimal
     maskedTextBox1.Mask = "AAAAA" 'Allows only 5 letters
     maskedTextBox1.Mask = "00/00/0000" 'NumbersIn Date Format
     maskedTextBox1.Mask = "0,00,000" 'Allows 6 Digit numberWith comma
     maskedTextBox1.Mask = "00:00" 'Numbers in Time Format
End Sub
 
 

Why use MaskedTextBox?

1. MaskedTextBox can validate user input to ensure it is valid.
2. Performing Custom validation is very easy.
3. The type of input you want at each position can be done very easily using MaskedTextBox.
4. It can be customize in a way that user will get beep if invalid input is given.
 
 

Screenshot

Using MaskedTextBox in C# and VB.Net
 
 

Downloads