Click here to Skip to main content
12,503,109 members (63,299 online)
Click here to Skip to main content
Add your own
alternative version

Stats

592.7K views
7.4K downloads
128 bookmarked
Posted

Masked C# TextBox Control

, 21 Jan 2004
Rate this:
Please Sign up or sign in to vote.
A control that can be used for date, IP address, phone number, SSN, digit and decimal format input

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

Share

About the Author

Jibin Pan
United States United States
No Biography provided

You may also be interested in...

Pro
Pro

Comments and Discussions

 
Questionabout new features Pin
glovkesh11-Sep-14 22:06
memberglovkesh11-Sep-14 22:06 
Questioncan someone help me Pin
babarkhalid24-Jun-14 21:52
memberbabarkhalid24-Jun-14 21:52 
Questionversion mask Pin
Chris Anders28-May-14 20:18
memberChris Anders28-May-14 20:18 
GeneralMy vote of 4 Pin
Feb1925-Feb-13 22:08
memberFeb1925-Feb-13 22:08 
Generalshamsi date(yyyy/mm/dd) [modified] Pin
ss_hellhound12-Nov-07 3:43
memberss_hellhound12-Nov-07 3:43 
QuestionCrystal Report for particullar where condition Pin
bagurtheen15-Feb-07 1:56
memberbagurtheen15-Feb-07 1:56 
GeneralMask for Email address Pin
ASysSolvers11-Dec-06 0:23
memberASysSolvers11-Dec-06 0:23 
GeneralRe: Mask for Email address Pin
Expert Coming16-Jun-07 13:01
memberExpert Coming16-Jun-07 13:01 
GeneralHuge Bug Pin
subhash_c14-Apr-06 14:53
membersubhash_c14-Apr-06 14:53 
QuestionHow to use with simple regular expression? Pin
Perry211-Apr-06 12:52
memberPerry211-Apr-06 12:52 
GeneralCopy/paste problem Pin
jfloviou20-Jul-05 7:43
sussjfloviou20-Jul-05 7:43 
Generalip problem Pin
ranjithlogics11-May-05 19:04
memberranjithlogics11-May-05 19:04 
GeneralMaskedTextBox in SharpDevelop Pin
fuese27-Apr-05 4:27
memberfuese27-Apr-05 4:27 
GeneralMask Ip... Pin
Rothariger18-Feb-05 7:31
memberRothariger18-Feb-05 7:31 
GeneralRe: Mask Ip... [modified] Pin
PandaPKH14-Jun-06 0:09
memberPandaPKH14-Jun-06 0:09 
GeneralError Provider help Pin
betterc11-Jul-04 3:27
memberbetterc11-Jul-04 3:27 
GeneralRe: Error Provider help Pin
betterc15-Aug-04 9:22
memberbetterc15-Aug-04 9:22 
GeneralRe: Error Provider help Pin
RogerDodge6-Nov-05 1:02
memberRogerDodge6-Nov-05 1:02 
GeneralRe: Error Provider help Pin
SmartGuest17-Jan-11 4:32
memberSmartGuest17-Jan-11 4:32 
GeneralGerman date Pin
sventek7-Jun-04 20:06
membersventek7-Jun-04 20:06 
GeneralRe: German date Pin
haezeban17-Jun-04 10:37
memberhaezeban17-Jun-04 10:37 
GeneralRe: German date Pin
haezeban17-Jun-04 11:07
memberhaezeban17-Jun-04 11:07 
GeneralRe: German date Pin
Anonymous16-Mar-05 11:48
sussAnonymous16-Mar-05 11:48 
GeneralA simple example for regular expression Pin
jian-ping18-Dec-03 14:30
memberjian-ping18-Dec-03 14:30 
Generaldate mask bug Pin
Emanuele Zambrano15-Dec-03 8:16
memberEmanuele Zambrano15-Dec-03 8:16 
GeneralSource code update Pin
Anonymous9-Dec-03 3:04
sussAnonymous9-Dec-03 3:04 
GeneralTextBOX enter event Pin
a_kas_2000@yahoo.com29-Oct-03 5:52
membera_kas_2000@yahoo.com29-Oct-03 5:52 
GeneralCars Pin
Oliver Jones28-Oct-03 4:15
memberOliver Jones28-Oct-03 4:15 
Questioncan someone help me to convert 'dateOnly' from format mm/dd/yyyy to dd/mm/yyyy? Pin
mistery2214-Oct-03 3:47
membermistery2214-Oct-03 3:47 
AnswerRe: can someone help me to convert 'dateOnly' from format mm/dd/yyyy to dd/mm/yyyy? Pin
dusty_bg15-Dec-03 20:29
memberdusty_bg15-Dec-03 20:29 
QuestionCan i acieve something like this with this control Pin
muzahm7-Sep-03 23:54
membermuzahm7-Sep-03 23:54 
AnswerRe: Can i acieve something like this with this control Pin
aprenot9-Nov-03 16:52
memberaprenot9-Nov-03 16:52 
GeneralSelectAll On Focus doesn't work anymore Pin
mistery225-Sep-03 12:39
membermistery225-Sep-03 12:39 
GeneralRe: SelectAll On Focus doesn't work anymore (also reply for: Very Nice Control - Small Bug) Pin
mistery225-Sep-03 22:50
membermistery225-Sep-03 22:50 
Questionbug? Pin
jayson_131-Jul-03 23:49
memberjayson_131-Jul-03 23:49 
GeneralMasked TextBox in web forms Pin
Sharmil.k18-Jun-03 2:25
sussSharmil.k18-Jun-03 2:25 
GeneralMasked TextBox Problem . . . Pin
Qarash3-Jun-03 9:36
memberQarash3-Jun-03 9:36 
GeneralRe: Masked TextBox Problem . . . Pin
jibinpan5-Jun-03 5:59
sussjibinpan5-Jun-03 5:59 
GeneralRe: Masked TextBox Problem . . . Pin
Qarash5-Jun-03 6:14
memberQarash5-Jun-03 6:14 
GeneralRe: Masked TextBox Problem . . . Pin
jonelster17-Jun-03 8:35
memberjonelster17-Jun-03 8:35 
GeneralRe: Masked TextBox Problem . . . Pin
Qarash17-Jun-03 8:46
memberQarash17-Jun-03 8:46 
GeneralRe: Masked TextBox Problem . . . Pin
jonelster17-Jun-03 8:53
memberjonelster17-Jun-03 8:53 
GeneralRe: Masked TextBox Problem . . . Pin
ek2503-Dec-03 13:18
memberek2503-Dec-03 13:18 
GeneralRe: Masked TextBox Problem . . . Pin
raop034-Dec-03 12:14
memberraop034-Dec-03 12:14 
GeneralRe: Masked TextBox Problem . . . Pin
MikeBergsma5-Dec-03 8:24
memberMikeBergsma5-Dec-03 8:24 
GeneralRe: Masked TextBox Problem . . . Pin
raop038-Dec-03 12:22
memberraop038-Dec-03 12:22 
GeneralRe: Masked TextBox Problem . . . Pin
takeoffeh9-Jan-04 4:52
membertakeoffeh9-Jan-04 4:52 
GeneralMicrosoft Masked Edit Control Pin
Romeo20-Mar-03 0:42
memberRomeo20-Mar-03 0:42 
GeneralRe: Microsoft Masked Edit Control Pin
Romeo27-Aug-03 5:55
memberRomeo27-Aug-03 5:55 
GeneralI Need help on Currency Formating Pin
Guru2kGh1-Mar-03 12:12
memberGuru2kGh1-Mar-03 12:12 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160919.1 | Last Updated 22 Jan 2004
Article Copyright 2001 by Jibin Pan
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid