Masked TextBox in C#
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
- Draw a TextBox in to your form
- Handle the KeyPress event of the TextBox
- Have a Regex object initialised to the mask pattern
- 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)
Leave a comment