How to allow only numbers in textbox


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).

5 responses to “How to allow only numbers in textbox

  1. Woah! I’m really loving the template/theme of this website. It’s
    simple, yet effective. A lot of times it’s hard to get that “perfect balance” between user friendliness and appearance. I must say you’ve done a great job
    with this. Additionally, the blog loads extremely quick for
    me on Opera. Outstanding Blog!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s