0

I need my text box to accept only number with one decimal point. I created a function to accept only numeric value. Now I need a help for accept only one decimal point:

private void txtOpenBal_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
    foreach (char ch in e.Text)
        if (!(Char.IsDigit(ch) || ch.Equals('.')))
        {
            e.Handled = true;
        }
}

It accept more than one decimal point

Kirill
  • 1,530
  • 5
  • 24
  • 48
Sabir
  • 235
  • 4
  • 15
  • You need to use regex. there are similar posts: http://stackoverflow.com/questions/23705423/regex-for-1-or-2-digits-with-one-optional-decimal-place http://stackoverflow.com/questions/308122/simple-regular-expression-for-a-decimal-with-a-precision-of-2 – ehh Jul 24 '15 at 05:38
  • You can try this http://stackoverflow.com/questions/16914224/wpf-textbox-to-enter-decimal-values – Dinesh balan Jul 24 '15 at 06:41

2 Answers2

1
private void TextBox_PreviewTextInput_1(object sender, TextCompositionEventArgs e)
    {
        // Here e.Text is string so we need to convert it into char
        char ch = e.Text[0];

        if ((Char.IsDigit(ch) || ch == '.'))
        {
            //Here TextBox1.Text is name of your TextBox
            if (ch == '.' && TextBox1.Text.Contains('.')) 
                e.Handled = true;
        }
        else
            e.Handled = true;
    }
Darshan Faldu
  • 1,471
  • 2
  • 15
  • 32
1

As @ehh said using regular expressions we can achive this.add the namespace System.Text.RegularExpressions;

private void TextBox_PreviewTextInput_1(object sender, TextCompositionEventArgs e)
    {
       Regex objregex = new Regex(@"^\d*\.\d{1}$");
       if (objregex.IsMatch(txtDomain.Text))
           {
             //do whatewer you want
           }    
  else
           { 
             //do whatewer you want
           }    

    }
shreesha
  • 1,811
  • 2
  • 21
  • 30