Click here to Skip to main content
6,594,432 members and growing! (16,896 online)
Email Password   helpLost your password?
Desktop Development » Edit Controls » General     Intermediate

Masked C# TextBox Control

By Jibin Pan

A control that can be used for date, IP address, phone number, SSN, digit and decimal format input
C#, Windows, .NET 1.0, .NET 1.1VS.NET2003, Dev
Posted:3 Nov 2001
Updated:21 Jan 2004
Views:317,318
Bookmarked:103 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
40 votes for this article.
Popularity: 6.06 Rating: 3.78 out of 5
2 votes, 6.3%
1
2 votes, 6.3%
2
5 votes, 15.6%
3
9 votes, 28.1%
4
14 votes, 43.8%
5

Introduction

The TextBox control is the most used control in a Windows program. It also cause a lot of problem either from QA or the user because of invalid data that was entered. Using a masked control will save a lot of time for the developer and reduce the complaints and bugs.

This masked intelligent user control enhances the function of the TextBox control, which can mask the Date, IP Address, SSN, Phone numbers, digits, decimal and checks the validation, and automatically set the delimiter location.

The property Masked is set to None by default and the control works like a normal TextBox control.
If setting the property to DateOnly, the control is masked to Date format.

It is intelligent.

What the user enters

What is Displayed

12 12/

124

12/04/

13

01/3

3

03/

34

03/04/

14

01/04/

1/

01/

Using the ErrorProvider to handle the invalidate input:

Creating Control:

  1. Start the Visual Studio.NET Windows Forms designer.
  2. Select a new C# project by clicking New from the File menu.
  3. Click Windows control library template on the templates.
  4. Set the Name MaskedTextBox

Then open the maskedTextBox.cs to Change the base class to the System.Windows.Forms.TextBox.

Adding a Property:

public enum Mask {None, DateOnly, PhoneWithArea, IpAddress, 
                  SSN, Decimal, Digit };
private Mask m_mask;
public Mask Maked
{
    get { return m_mask;}
    set {
        m_mask = value;
        this.Text="";
    }
}

Override the OnKeyPress function

      this.KeyPress += new                                             
                    KeyPressEventHandler(this.OnKeyPress);             

      private void OnKeyPress(object sender, KeyPressEventArgs e)
      {                                                          
            MaskedTextBox sd = (MaskedTextBox) sender;           
            if (sd.m_IPAddrOnly)                                 
                  sd.MaskIpAddr(e);                              
            if (sd.m_digitOnly)                                  
                  sd.MaskDigit(e);                               
            if(sd.m_ssn)                                         
                  sd.MaskPhoneSSN(e, 3, 2);                      
            if(sd.m_phoneOnly)                                   
                  sd.MaskPhoneSSN(e, 3, 3);                      
            if(sd.m_dateOnly)                                    
                  sd.MaskDate(e);                                
            if(sd.m_decimalOnly)                                 
                  sd.MaskDecimal(e);                             
      }    

Unboxing the sender and using it to call these function is very important for multiple properties and when more than one control is used in one form, otherwise different controls may share the same variable with another control, which will cause unexpected results.

Double check the masked format:

private void OnLeave(object sender, EventArgs e)            
{                                                           
    MaskedTextBox sd = (MaskedTextBox) sender;            
    Regex regStr;                                         
    switch(m_mask)                                        
    {                                                     
        case Mask.DateOnly:                             
            regStr = new Regex(@"\d{2}/\d{2}/\d{4}"); 
            if(!regStr.IsMatch(sd.Text))              
                errorProvider1.SetError(this, "*"); 
            break;                                    

        case Mask.PhoneWithArea:                        
            regStr = new Regex(@"\d{3}-\d{3}-\d{4}"); 
            if(!regStr.IsMatch(sd.Text))              
                errorProvider1.SetError(this,"**"); 
            break;                                    

        case Mask.IpAddress:                            
            short cnt=0;                              
            int len = sd.Text.Length;                 
            for(short i=0; i<len;i++)                 
                if(sd.Text[i] == '.')               
                {                                   
                    cnt++;                        
                    if(i+1 < len)                 
                        if(sd.Text[i+1] == '.') 
                        {                       
                            errorProvider1.SetError(this, "*"); 
                            break;            
                        }                       
                    }                                   
                    if(cnt < 3 || sd.Text[len-1] == '.')      
                        errorProvider1.SetError(this, "*"); 
                    break;        
                                                
        case Mask.SSN:                                  
            regStr = new Regex(@"\d{3}-\d{2}-\d{4}"); 
            if(!regStr.IsMatch(sd.Text))              
                errorProvider1.SetError(this, "*"); 
            break;     
                                           
        case Mask.Decimal:                              
            break;                                    

        case Mask.Digit:                                
            break;                                    
    }                                                     
}   

Usage

After creating the DLL program, you should add the component into ToolBox. By:

  1. Right click the mouse in the ToolBox, and then select Customize Toolbox to open a dialog.
  2. Select the tab .Net framework component,
  3. Use the browser to find your DLL, check it, then click Ok.

The control should be in the ToolBox and it is ready to use.

That is all. I hope you enjoy it.

History:

Update at 03/04/2002.
Using enum to set the properties.
Add Onleave function to check the invalidation of the controls.
Add Leap year check for Date mask in the CheckDayOfMonth funcrion.

12 July 2002 - updated source download

9 Nov 2003 - updated source download

If you have any comments or find some bugs, I would love to hear about it and make it better. You can reach me at Jibin Pan.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Jibin Pan


Member

Location: United States United States

Other popular Edit Controls articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 69 (Total in Forum: 69) (Refresh)FirstPrevNext
Generalshamsi date(yyyy/mm/dd) [modified] Pinmemberss_hellhound4:43 12 Nov '07  
QuestionCrystal Report for particullar where condition Pinmemberbagurtheen2:56 15 Feb '07  
GeneralMask for Email address PinmemberASysSolvers1:23 11 Dec '06  
GeneralRe: Mask for Email address PinmemberExpert Coming14:01 16 Jun '07  
GeneralHuge Bug Pinmembersubhash_c15:53 14 Apr '06  
GeneralHow to use with simple regular expression? PinmemberPerry213:52 11 Apr '06  
GeneralCopy/paste problem Pinsussjfloviou8:43 20 Jul '05  
Generalip problem Pinmemberranjithlogics20:04 11 May '05  
GeneralMaskedTextBox in SharpDevelop Pinmemberfuese5:27 27 Apr '05  
GeneralMask Ip... PinmemberRothariger8:31 18 Feb '05  
GeneralRe: Mask Ip... [modified] PinmemberPandaPKH1:09 14 Jun '06  
GeneralError Provider help Pinmemberbetterc4:27 11 Jul '04  
GeneralRe: Error Provider help Pinmemberbetterc10:22 15 Aug '04  
GeneralRe: Error Provider help PinmemberRogerDodge2:02 6 Nov '05  
GeneralGerman date Pinmembersventek21:06 7 Jun '04  
GeneralRe: German date Pinmemberhaezeban11:37 17 Jun '04  
GeneralRe: German date Pinmemberhaezeban12:07 17 Jun '04  
GeneralRe: German date PinsussAnonymous12:48 16 Mar '05  
GeneralA simple example for regular expression Pinmemberjian-ping15:30 18 Dec '03  
Generaldate mask bug PinmemberEmanuele Zambrano9:16 15 Dec '03  
GeneralSource code update PinsussAnonymous4:04 9 Dec '03  
GeneralTextBOX enter event Pinmembera_kas_2000@yahoo.com6:52 29 Oct '03  
GeneralCars PinmemberOliver Jones5:15 28 Oct '03  
Generalcan someone help me to convert 'dateOnly' from format mm/dd/yyyy to dd/mm/yyyy? Pinmembermistery224:47 14 Oct '03  
GeneralRe: can someone help me to convert 'dateOnly' from format mm/dd/yyyy to dd/mm/yyyy? Pinmemberdusty_bg21:29 15 Dec '03  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 21 Jan 2004
Editor: Nishant Sivakumar
Copyright 2001 by Jibin Pan
Everything else Copyright © CodeProject, 1999-2009
Web21 | Advertise on the Code Project