Wednesday, December 06, 2006

Restricting a textbox...

...using regular expressions

the following event handler is attached to a textbox that is only allowed to have digits in it


using System.Text.RegularExpressions;


private void mileageTextBox_TextChanged(object sender, EventArgs e)
{
// choose which characters are not allowed
string pattern = "[^0-9]";

// this anonymous function replaces a character from the pattern string
// (a match) with the empty string (i.e. it removes that character)
MatchEvaluator me = delegate { return string.Empty; };

// perform actual replacement of all occurences of any character
// from the pattern string with the empty string
mileageTextBox.Text = Regex.Replace(mileageTextBox.Text, pattern, me);
}

No comments: