If we have the requirement – ” texbox should only accept numbers 0-9″, we cant do it directly as there is no property to make the textbox default string acceptance behaviour into digits or decimal or integer.
Just right the following code and you will be able to achieve the goal -
XAML -
<TextBox x:Name=”mytxtbox” Height=”26″ Width=”50″ KeyDown=”mytxtbox_KeyDown”/>
XAML.cs
private void mytxtbox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Tab)
{
}
else
{
var thisKeyStr = “”;
if (e.PlatformKeyCode == 190 || e.PlatformKeyCode == 110)
{
thisKeyStr = “.”;
}
else
{
thisKeyStr = e.Key.ToString().Replace(“D”, “”).Replace(“NumPad”, “”);
}
var s = (sender as TextBox).Text + thisKeyStr;
var rStr = “^[0-9]+[.]?[0-9]*$”;
var r = new Regex(rStr, RegexOptions.IgnoreCase);
e.Handled = !r.IsMatch(s);
}
}
HOW DO WE ACHIVE THIS ? WHAT WE HAVE DONE HERE ??
- First we check to see if the keycode is 190 or 110 (the decimal key on the keyboard and the numpad, respectively) and set the string (thisKeyStr) to “.”.
- If not, we capture the key currently being pressed.
- We then do a replace of “D” and “NumPad” to remove the string prefixes on the keycode leaving just the number being pressed.
- Next, we create a test string from the TextBox.Text property and the thisKeyStr string to test the current value plus the key being pressed to see if want to allow the keystroke.
- We then use a Regex to determine if the string matches the pattern (line boundary > any number of numbers > optional decimal point > optional additional numbers after the decimal point > line boundary),
This will allow only one decimal point in the overall expression. We return the inverse of the regex match since we want to ignore the key stroke if a wrong key was pressed.
NOTE : You may need to tweak the regex piece a bit, but it works under all Windows platforms (due to the use of the PlatformKeyCode value which may be different in a Mac/Unix environment).
It is working Great but “d”.