0

How to make a xaml textbox in silverlight accept only numbers with maximum one decimal point precison. I have tried the answers in this question How to make a textBox accept only Numbers and just one decimal point in Windows 8. But it did not work. How can I do this ?

1
  • Can you put your xaml and cs page stuff ? Aug 8, 2015 at 4:27

1 Answer 1

1

You can write a function like this,

 txtDiscount.KeyDown += new KeyEventHandler(EnsureNumbers);

//Method to allow only numbers,

void EnsureNumbers(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Tab)
        {
            return; 
        }
        bool result =  EnsureDecimalPlaces();
        if (result == false)
        {
            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);
        }
        else
        {
            e.Handled = true;
        }
    }

Method to ensure only 1 decimal,

  bool EnsureDecimalPlaces()
    {

        string inText = txtDiscount.Text;
        int decPointIndex = inText.IndexOf('.');
        if (decPointIndex < 1 || decPointIndex == 1)
        {
            return false;
        }
        else
            return true;
    }
6
  • how can i use this function for multiple text boxes. Is there any way ? Aug 8, 2015 at 3:58
  • call the function in the textchanged event of those boxes Aug 8, 2015 at 3:59
  • so i need to set variable intext to ((Textbox)sender).Text ? Aug 8, 2015 at 4:01
  • this function is accepting alphabets also.. how to remove that and after inputting the first number after the decimal point if i try to insert another number the number is appending to the number before decimal point. I need nothing to be entered in the textbox after the first decimal precision. How to do that Aug 8, 2015 at 4:09
  • Let us continue this discussion in chat. Aug 8, 2015 at 4:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.