Thursday, March 17, 2011

C# TextBox input values with decimal places

This code shows how to make a textbox that let's user input values with decimal places.

1. Create a textbox and name in "textBox".
2. Create a keypress event.
3. copy and paste the code below. ( the code lets the user input numbers up to two decimal places ).

// check if key pressed is numeric, backspace or decimal character " . "


if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), "\\d+") 
&& e.KeyChar != (char)Keys.Back && e.KeyChar != '.')
   {        e.Handled = true;    } if (e.KeyChar == '.')    {        if (textBox.Text.Contains('.'))        {            e.Handled = true;           return;        }                   }
 if (System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), "\\d+"))   {     if (textBox.Text.Contains('.'))      {             // - 3 is for the decimal places. 
//You may make it 4 or 5 depends on your application             if (textBox.Text.IndexOf('.') == textBox.Text.Length - 3)             e.Handled = true;        }    }

No comments:

Post a Comment

Related Posts with Thumbnails