Programmers’ Log

foreach(Snippet aSnippet in ProgrammersLog){ aSnippet.GetSolution(); }

Masked TextBox in C#

leave a comment »

Masked TextBoxes are those that won’t allow (or that will allow) certain strings, numbers or characters or patterns. Such kind of control is already present in the C#.Net with the name MaskedTextBox. This tutorial will suggest another way of doing such a TextBox in simple steps.

We will be using Regex in this tutorial. Its suggested that you have a look at the keywords used in writing Regex patterns [ RegularExpressions ].
RegexPal is an online regex tester. Its really handy at times.

Follow these steps to get a custom made masked textbox. We will be using Regex for specifying the mask

  1. Draw a TextBox in to your form
  2. Handle the KeyPress event of the TextBox
  3. Have a Regex object initialised to the mask pattern
  4. In the KeyPress handler use the Handled property of the KeyPressEvent to decide on whether to accept the key that has been pressed or not

Make sure that your Regex has ^ and $ at the beginning and end of the pattern

For example,

using System.Windows.Forms;

TextBox myCustomMaskedTextBox = new TextBox();
this.Controls.Add(myCustomMaskedTextBox);

Regex myPattern = new Regex(@"^[0-9]*$");
myCustomMaskedTextBox.KeyPress += new System.Windows.Forms.KeyPressEventHandler(CustomTextBoxKeyPressed);

private void CustomTextBoxKeyPressed(object sender, KeyPressEventArgs args)
{
//to allow the backspace key for deletion of the characters
if(args.KeyChar = '\b')
{
string t= myCustomMaskedTextBox.Text + args.KeyChar.ToString();
if(myRegex.IsMatch(t))
{
//pass
}
else
{
args.Handled = true;
}
}
}

The above snippet will allow the user to enter only numbers in to the textbox. Nothing else (except backspace)

Written by sudarsanyes

July 3, 2008 at 1:00 am

Posted in C#, Controls, Regex, UI

Tagged with , ,

Leave a comment