Windows Forms 2.0 – The MaskedTextBox Control Recipes

Posted by: Suprotim Agarwal , on 3/19/2007, in Category WinForms & WinRT
Views: 42597
Abstract: In this article, we will explore how to perform some common tasks using the MaskedTextBox Control of Windows Forms 2.0.
Windows Forms 2.0 – MaskedTextBox Control Recipes
 
The System.Windows.Forms.MaskedTextBox Control is a TextBox with a mask feature. It allows you to restrict the input from a user and provides a mask to help the user enter data in a particular format. A list of useful masks is available using the Mask editor. This editor also lets a developer create custom masks and test the chosen mask as shown in the figure in the below section.
How Do I Get Started With The MaskedTextBox Control
 
Let us take an example and see how the MaskedTextBox can be used in your application
 
Using the Designer
To add a MaskedTextBox control to your form, follow these steps :
1.    Drag a MaskedTextBox control from the Toolbox to your form.
2.    In the Properties window, select the Mask property and click the ... (ellipsis) button next to the property name.
3.    In the Input Mask dialog box, select the Short Date mask and click OK.
4.    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.
 
 
 
 
Programatically
The Mask property of MaskedTextBox allows you to set the Mask programmatically. The following code sets masks programmatically, and achieves what we have demonstrated in the above sample using Input Mask dialog. The following code example initializes the MaskedTextBox to accept a Zip Code, and uses both the MaskInputRejected event to alert the user to invalid input.
 
private void CreateMaskedTextBox()
{
mtb = new MaskedTextBox();
mtb.Location = new Point(30, 30);
mtb.Mask = "00000-9999"; // For Zip Code
mtb.MaskInputRejected += new MaskInputRejectedEventHandler(mtb_MaskInputRejected);
Controls.Add(mtb);
 
 
}
 
void mtb_MaskInputRejected(object sender, MaskInputRejectedEventArgs e)
 
{
// Add a namespace System.Media;
// System sounds a beep every time the user attempts to input
// an invalid character
SystemSounds.Beep.Play();
}
 
Note: When you change the Culture property on the MaskedTextBox, the Mask picker dialog will show the pre-defined masks for that culture.
 
How Do I Create A Custom MaskedTextBox
 
You can create your own mask using the special mask characters shown in the table below taken from MSDN:
 
Masking element
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. If the AsciiOnly property is set to true, this element behaves like the "L" element.
C
Character, optional. Any non-control character. If the AsciiOnly property is set to true, this element behaves like the "?" element.
A
Alphanumeric, optional. If the AsciiOnly property is set to true, the only characters it will accept are the ASCII letters a-z and A-Z.
a
Alphanumeric, optional. If the AsciiOnly property is set to true, the only characters it will accept are the ASCII letters a-z and A-Z.
.
Decimal placeholder. The actual display character used will be the decimal placeholder 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.
:
Time separator. The actual display character used will be the time placeholder appropriate to the format provider, as determined by the control's FormatProvider property.
/
Date separator. The actual display character used will be the date placeholder appropriate to the format provider, as determined by the control's FormatProvider property.
$
Currency symbol. The actual character displayed will be the currency symbol appropriate to the format provider, as determined by the control's FormatProvider property.
< 
Shift down. Converts all characters that follow to lowercase.
>
Shift up. Converts all characters that follow to uppercase.
|
Disable a previous shift up or shift down.
\
Escape. Escapes a mask character, turning it into a literal. "\\" is the escape sequence for a backslash.
All other characters
Literals. All non-mask elements will appear as themselves within MaskedTextBox. Literals always occupy a static position in the mask at run time, and cannot be moved or deleted by the user.
 
The following code example initializes the MaskedTextBox to accept a currency value in the range of 0 to 9999, and uses both the MaskInputRejected and event to alert the user to invalid input.
 
private void CreateCustomMaskedTextBox()
{
mtb = new MaskedTextBox();
mtb.Location = new Point(30, 60);
mtb.Mask = "$9,999.00" ; // A custom mask value to restrict a currency value in the range of 0 to 9999
mtb.MaskInputRejected += new MaskInputRejectedEventHandler(mtb_MaskInputRejected);
Controls.Add(mtb);
}
 
private void btnCustom_Click(object sender, EventArgs e)
{
CreateCustomMaskedTextBox();
}
 
Conclusion :
 
In this article, we saw a recipe approach to performing some of the most common tasks with the MaskedTextBox Control. I hope the article was useful and I thank you for viewing it.
 

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and The Absolutely Awesome jQuery CookBook.

Suprotim received the prestigious Microsoft MVP award for 17 consecutive years, until he resigned from the program in 2025. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.

Get in touch with him on Twitter @suprotimagarwal or at LinkedIn



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Niharika on Monday, March 10, 2008 4:00 PM
I want code for masked textbox werin the int id is dynamically generated once d form is loaded. The id shud be unique and dynamically generated wen form is loaded each time.
i am usin ASP.net and C# for codin
$(this).siblings('.current').removeClass('current'); $(this).addClass('current'); $('.tabContent').children('.current').removeClass('current'); $('.tabContent').children().eq($(this).index()).addClass('current'); }); });