Blue Theme Orange Theme Green Theme Red Theme
 
Team Foundation Server Hosting
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Mindcracker MVP Summit 2012
Search :       Advanced Search »
Home » Windows Controls C# » MaskedTextBox in C#

MaskedTextBox in C#

In this article, I will discuss how to create a MaskedTextBox control in Windows Forms at design-time as well as run-time.

Author Rank :
Page Views : 18281
Downloads : 279
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
MaskedTextBoxSampleInCSharp.zip
 
 
Team Foundation Server Hosting
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


A MaskedTextBox control provides validation mechanism for user input on a Form. For example, if you want a TextBox to accept date in mm/dd/yyyy format, you can set masking in the MaskedTextBox.  

In this article, I will discuss how to create a MaskedTextBox control in Windows Forms at design-time as well as run-time. After that, I will continue discussing various properties and methods available for the MaskedTextBox control.

Creating a MaskedTextBox

We can create a MaskedTextBox control using a Forms designer at design-time or using the MaskedTextBox class in code at run-time (also known as dynamically).

To create a MaskedTextBox control at design-time, you simply drag and drop a MaskedTextBox control from Toolbox to a Form in Visual Studio. After you drag and drop a MaskedTextBox on a Form,

the MaskedTextBox looks like Figure 1. Once a MaskedTextBox is on the Form, you can move it around and resize it using mouse and set its properties and events.

MaskedTextBoxImg1.jpg

Figure 1

Creating a MaskedTextBox control at run-time is merely a work of creating an instance of MaskedTextBox class, set its properties and add MaskedTextBox class to the Form controls.

First step to create a dynamic MaskedTextBox is to create an instance of MaskedTextBox class. The following code snippet creates a MaskedTextBox control object.

MaskedTextBox dynamicMaskedTextBox = new MaskedTextBox();

 

In the next step, you may set properties of a MaskedTextBox control. The following code snippet sets background color, foreground color, Text, Name, and Font properties of a MaskedTextBox.

dynamicMaskedTextBox.BackColor = Color.Red;

dynamicMaskedTextBox.ForeColor = Color.Blue;

         

dynamicMaskedTextBox.Text = "I am Dynamic MaskedTextBox";

dynamicMaskedTextBox.Name = "DynamicMaskedTextBox";

dynamicMaskedTextBox.Font = new Font("Georgia", 16);

 

Once a MaskedTextBox control is ready with its properties, next step is to add the MaskedTextBox control to the Form. To do so, we use Form.Controls.Add method. The following code snippet adds a MaskedTextBox control to the current Form.

 

Controls.Add(dynamicMaskedTextBox); 

 

Setting MaskedTextBox Properties

After you place a MaskedTextBox control on a Form, the next step is to set properties.

The easiest way to set properties is from the Properties Window. You can open Properties window by pressing F4 or right click on a control and select Properties menu item. The Properties window looks like Figure 2.

MaskedTextBoxImg2.jpg

Figure 2

Location, Height, Width, and Size

The Location property takes a Point that specifies the starting position of the MaskedTextBox on a Form. The Size property specifies the size of the control. We can also use Width and Height property instead of Size property. The following code snippet sets Location, Width, and Height properties of a MaskedTextBox control.

dynamicMaskedTextBox.Location = new Point(20, 150);

dynamicMaskedTextBox.Height = 40;

dynamicMaskedTextBox.Width = 300;

Background, Foreground, BorderStyle

BackColor and ForeColor properties are used to set background and foreground color of a MaskedTextBox respectively. If you click on these properties in Properties window, the Color Dialog pops up.

Alternatively, you can set background and foreground colors at run-time. The following code snippet sets BackColor and ForeColor properties.

dynamicMaskedTextBox.BackColor = Color.Red;

dynamicMaskedTextBox.ForeColor = Color.Blue;

You can also set borders style of a MaskedTextBox by using the BorderStyle property. The BorderStyle property is represented by a BorderStyle enumeration that has three values – FixedSingle, Fixed3D, and None.  The default value of border style is Fixed3D. The following code snippet sets the border style of a MaskedTextBox to FixedSingle.

dynamicMaskedTextBox.BorderStyle = BorderStyle.FixedSingle;

Name

Name property represents a unique name of a MaskedTextBox control. It is used to access the control in the code. The following code snippet sets and gets the name and text of a MaskedTextBox control.

dynamicMaskedTextBox.Name = "DynamicMaskedTextBox";

string name = dynamicMaskedTextBox.Name;

Text, TextAlign, and TextLength

Text property of a MaskedTextBox represents the current text of a MaskedTextBox control. The TextAlign property represents text alignment that can be Left, Center, or Right. The TextLength property returns the length of a MaskedTextBox contents.

The following code snippet sets the Text and TextAlign properties and gets the size of a MaskedTextBox control.

dynamicMaskedTextBox.Text = "I am Dynamic MaskedTextBox";

dynamicMaskedTextBox.TextAlign  = HorizontalAlignment.Center;

int size = dynamicMaskedTextBox.TextLength;

Font

Font property represents the font of text of a MaskedTextBox control. If you click on the Font property in Properties window, you will see Font name, size and other font options. The following code snippet sets Font property at run-time.

dynamicMaskedTextBox.Font = new Font("Georgia", 16);

Maximum Length

You can restrict number of characters in a MaskedTextBox control by setting MaxLength property. The following code snippet sets the maximum length of a MaskedTextBox to 50 characters.

dynamicMaskedTextBox.ReadOnly = true;

dynamicMaskedTextBox.MaxLength = 50;

 

Masking Related Properties

Mask

Mask the default property and represents the format of the input can be accepted by a control. We can set Mask property by clicking on the control and click on the little handler and select Set Mask link as you can see in Figure 3.

MaskedTextBoxImg3.jpg

Figure 3

Set Mask launches Input Mask dialog where we can select a mask and you can see its data format and also set the validation type. See Figure 4.

MaskedTextBoxImg4.jpg

Figure 4

The following code snippet sets the Mask property at run-time.

 

dynamicMaskedTextBox.Mask = "00/00/0000";

 

Here is a list and description of masking characters.

0 – Digit, required. Value 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.

L - Letter, required. Restricts input to the ASCII letters a-z and A-Z.

? - Letter, optional. Restricts input to the ASCII letters a-z and A-Z.

& - Character, required.

C - Character, optional. Any non-control character.

A - Alphanumeric, required.

a - Alphanumeric, optional.

.  - Decimal placeholder.

, - Thousands placeholder.

: - Time separator.

/ - Date separator.

$ - Currency symbol.

< - 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.

MaskFull

MaskFull property represents if the mask values are completed.

if (maskedTextBox1.MaskFull){}

BeepOnError

If set true, the system beep is generated when incorrect values are entered.

dynamicMaskedTextBox.BeepOnError = true;

 

Summary

A MaskedTextBox control accepts user input on a Form. In this article, we discussed discuss how to create a MaskedTextBox control in Windows Forms at design-time as well as run-time. After that, we saw how to use various properties and methods.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Mahesh Chand
Mahesh is the founder of C# Corner and Mindcracker Network, an author of several .NET programming books and a Microsoft MVP for 6 consecutive years. In his day to day work, Mahesh is a Senior Software Consultant with over 14 years of IT industry experience building systems for Financial and Banking, Engineering & Architectural, Imaging, Construction, Biological & Pharmaceuticals, Healthcare and Education industries. His expertise is Windows Forms, ASP.NET, Silverlight, WPF, WCF, Visual Studio 2010, SQL Server, and Oracle.  If you are looking for a Sharepoint, Windows Forms, ASP.NET, WPF, Silverlight, C#, VB.NET, Oracle, and SQL Server Consultant in Philadelphia area or remote location, drop me a line at MAHESH [AT] C-SHARPCORNER [DOT] COM.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Nevron Chart
Become a Sponsor
 Comments
setting dd/mm/yyyy format in masked textbox by Mayur On November 1, 2010
I want to set date format as dd/mm/yyyy how can we do it.
when i write maskedtextbox1.text=datetime.now.tostring it is getting format as mm/dd/yyyy
Reply | Email | Modify 
masked textbox problem by Tania On December 6, 2010

Hi everybody,

I'm using a masked textbox for my Date like this : 01/12/2010

Now the problem is, when the user uses a date with a leading 0, the masked textbox gives this 11/22/010_

So it skipped the leading 0 althought it is correct in my database.

This is the code I use to fill the masked textbox :

mtbShipDate.Text = Convert.ToString(dataRowData["ShipDate"]);

Please can somebody help me?

Thanks,

Tania

Reply | Email | Modify 
Discover the top 5 tips for understanding .NET Interop
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.