Walkthrough: Working with the MaskedTextBox Control
Tasks illustrated in this walkthrough include:
-
Initializing the MaskedTextBox control
-
Using the MaskInputRejected event handler to alert the user when a character does not conform to the mask
-
Assigning a type to the ValidatingType property and using the TypeValidationCompleted event handler to alert the user when the value they're attempting to commit is not valid for the type
To add a MaskedTextBox control to your form
-
Open the form on which you want to place the MaskedTextBox control.
-
Drag a MaskedTextBox control from the Toolbox to your form.
-
Right-click the control and choose Properties. In the Properties window, select the Mask property and click the ... (ellipsis) button next to the property name.
-
In the Input Mask dialog box, select the Short Date mask and click OK.
-
In the Properties window set the BeepOnError property to true. This property causes a short beep to sound every time the user attempts to input a character that violates the mask definition.
For a summary of the characters that the Mask property supports, see the Remarks section of the Mask property.
Add a balloon tip for rejected mask input
-
Return to the Toolbox and add a ToolTip to your form.
-
Create an event handler for the MaskInputRejected event that raises the ToolTip when an input error occurs. The balloon tip remains visible for five seconds, or until the user clicks it.
public void Form1_Load(Object sender, EventArgs e) { ... // Other initialization code maskedTextBox1.Mask = "00/00/0000"; maskedTextBox1.MaskInputRejected += new MaskInputRejectedEventHandler(maskedTextBox1_MaskInputRejected) } void maskedTextBox1_MaskInputRejected(object sender, MaskInputRejectedEventArgs e) { toolTip1.ToolTipTitle = "Invalid Input"; toolTip1.Show("We're sorry, but only digits (0-9) are allowed in dates.", maskedTextBox1, maskedTextBox1.Location, 5000); }
Add a balloon tip for invalid data types
-
In your form's Load event handler, assign a Type object representing the DateTime type to the MaskedTextBox control's ValidatingType property:
-
Add an event handler for the TypeValidationCompleted event:
public void maskedTextBox1_TypeValidationCompleted(object sender, TypeValidationEventArgs e) { if (!e.IsValidInput) { toolTip1.ToolTipTitle = "Invalid Date Value"; toolTip1.Show("We're sorry, but the value you entered is not a valid date. Please change the value.", maskedTextBox1, 5000); e.Cancel = true; } }