MaskedTextBox Tutorial: Windows Forms .NET

When creating Windows Forms programs that accept input, you often need to ensure that the input is of a specific format. For example, you need phone numbers to have their area code and also the correct number of digits. To solve this problem, you can use the MaskedTextBox control.

This C# tutorial shows how to use the MaskedTextBox control in Windows Forms.

MaskedTextBox control

Get started (MaskInputRejected)

Note

To get started, please add a MaskedTextBox control to your Windows Forms program by double-clicking on the icon in the toolbox. Next, try changing the properties of the MaskedTextBox by right-clicking on it and selecting properties. Importantly, change the Mask property: you can find predefined masks for integer numbers, phone numbers, dates in various formats, Social Security Numbers, time in various formats, and zip codes. This tutorial shows the MaskedTextBox with the Social Security Number format specified.

Example program for MaskedTextBox [C#]

using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
	public Form1()
	{
	    InitializeComponent();
	}

	private void maskedTextBox1_MaskInputRejected(object sender, MaskInputRejectedEventArgs e)
	{
	    // Set the window title text to the MaskInputRejectedEventArgs information.
	    this.Text = "Error: " +
		e.RejectionHint.ToString() +
		"; position: " +
		e.Position.ToString();
	}
    }
}

Using MaskInputRejected event handler. The example shows the MaskInputRejected event handler, and you can add this by double-clicking on the MaskedTextBox control. In this implementation, we simply change the window text to show the RejectionHint and also the Position of the error. This clues in the user as to the nature of the error.

Validation (TypeValidationCompleted)

The MaskedTextBox can do more than simply ensure a format is followed: it can convert the input into a C# type for you as well. In this example, we set the format to the "Short date" mask pattern. Then, we added the TypeValidationCompleted event handler by going to the event list in Visual Studio.

Example program 2 for MaskedTextBox [C#]

using System;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
	public Form1()
	{
	    InitializeComponent();
	}

	private void maskedTextBox1_TypeValidationCompleted(object sender, TypeValidationEventArgs e)
	{
	    // This event is raised when the enclosing window is closed.
	    // ... We show a MessageBox that details the DateTime.
	    DateTime value = (DateTime)e.ReturnValue;
	    MessageBox.Show("Validated: " + value.ToLongDateString());
	}
    }
}
Dialog

Casting the ReturnValue object. To get the validated result, please access the ReturnValue property from the TypeValidationEventArgs parameter. You will need to cast this object. The TypeValidationCompleted event handler is triggered when the form is dismissed; this is most useful for dialogs.

Properties

Note

There are several more properties you can adjust on the MaskedTextBox control. In this section, we examine most of them in brief to give an overview of which ones might be useful to you.

AsciiOnly property. The AsciiOnly property enforces that every character entered not be an accented or Unicode-only character. This is actually very useful when you require strict data input, as many database systems do not need non-ASCII characters.

CutCopyMaskFormat property. In some programs, users will want to copy the text from a MaskedTextBox to their clipboards. This property lets you adjust how the text will be copied: you can specify whether the separators should be included in the copied text.

HidePromptOnLeave and HideSelection properties. These two boolean properties determine how the MaskedTextBox is adjusted when the user focuses another control in the form. You could create a simpler, more streamlined user interface by hiding some of the prompt characters when they are not needed.

PasswordChar and PromptChar properties. The MaskedTextBox lets you change the character that appears when a password is entered; it also allows you to change the prompt character. By default, the prompt character is an underscore (_); depending on your program, you can use a hyphen (-) or even an asterisk (*).

ResetOnPrompt and ResetOnSpace properties. These two properties are usability features of the MaskedTextBox control. When you have a mask, there will be some prompt characters such as / or _. If your user types either of those characters, and the position of the MaskedTextBox has one of those characters, this will be considered valid input. Please set both properties to True to enable this usability feature.

UseSystemPasswordChar property. Finally, you can use the system-defined password character for when your MaskedTextBox is a password box. Typically, this is an asterisk or a bullet character.

Summary

The C# programming language

The MaskedTextBox control in Windows Forms enforces the range of input that is allowed into the text box. It is ideal for when you want to collect phone numbers, identification numbers, dates or times, or even simple integers. Implementing these same features is much harder if you use the plain TextBox; the MaskedTextBox truly makes life easier for these strict cases.

TextBox Tutorial Windows Forms
.NET