Masked C# TextBox Control


Download MaskedTextBox_src.zip

The TextBox control is the most used controlin window program. It also cause a lot of problem either from QA oruser, because invalid data that was entered. Using masked control willsave a lot of time for developer and reduce the bugs.

This masked intelligent user control enhancesthe function of TextBox control, which can mask the Date, IP Address,SSN, Phone number, digit, decimal and check the validation,automatically set delimit location.

All these properties are set to false by default and the control works like a normal TextBox control.

Setting the property DateOnly to true, the control is masked to Date format.

It is intelligent.

 

When user enter Display
12 12/
124 12/04/
13 01/3
3 03/
34 03/04/
14 01/04/
1/ 01/

Using the ErroProvider 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:

private bool m_dateOnly;
private bool m_phoneOnly;
private bool m_IPAddrOnly;
private bool m_ssn;
private bool m_decimalOnly;

private bool m_digitOnly;

public bool DateOnly
{
get { return m_dateOnly; }
set { m_dateOnly= value;}
}

Overwrite 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 callthese function are very important for multiple properties and more thanone control are used in one form, otherwise different control may sharesame variable with other control, that will cause the unexpectedresults.

Usage:

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

Right click the mouse in the ToolBox, and thenselect Customize Toolbox to open a dialog. Select the tab .Netframework component, using browser to find your DLL, check it, thenclick Ok. The control should be in the ToolBox that is ready to use.

Note:

Only one of the properties should be set to true, otherwise the control will work incorrectly.

That is all.

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

I was C/C++/MFC programmer at Interactive Edge Corp. Xtend Communications Corp.

MoneyLine Corp in New York City since 1994 and has Master degree at computer science.

Twitter Digg Delicious Stumbleupon Technorati Facebook Email

No comments yet... Be the first to leave a reply!