1
Answer

Textbox validation for amount

I want to check a textbox value where value have to positive or negative.. negative input value should -10.25, -0.20,-6 etc these patern. and also positive  input value should 1.25, 0.50, 5 etc these patarn. I want to validate onKeyPress Event..
Answers (1)
0
Manas Mohapatra

Manas Mohapatra

NA 29.3k 3.3m 7y
Did you try like this:
 
You nned to attach an keypress event in textbox properties. 
 
http://csharp.net-informations.com/gui/key-press-cs.htm 
  1. private void textBox1_KeyPress(object sender, KeyPressEventArgs e)  
  2. {  
  3.   
  4.     if (!char.IsControl(e.KeyChar) && (!char.IsDigit(e.KeyChar))   
  5.         && (e.KeyChar != '.')  && (e.KeyChar != '-'))  
  6.         e.Handled = true;  
  7.   
  8.     // only allow one decimal point  
  9.     if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)  
  10.         e.Handled = true;  
  11.   
  12.     // only allow minus sign at the beginning  
  13.     if (e.KeyChar == '-' && (sender as TextBox).Text.Length > 0)  
  14.         e.Handled = true;  
  15.       
  16.     if (e.KeyChar == 13 || e.KeyChar == (char)Keys.Enter)  
  17.     {  
  18.         try  
  19.         {  
  20.             double myDouble = double.parse(TextBox1.Text)  
  21.         }  
  22.         catch (Exception e)  
  23.         {  
  24.             MessageBox.Show("Input is incorrect""Error");  
  25.               
  26.             // make textBox1 blank and red as border..  
  27.             TextBox1.Text = "";       
  28.         }  
  29.     }  
  30.       
  31.     // OR try like this  
  32.     var regex = new Regex("^[-]?\d+(\.\d+)?$", RegexOptions.Compiled);  
  33.     Match m = regex.Match(TextBox1.Text + e.KeyChar);  
  34.     if(!m.Success)  
  35.     {  
  36.         MessageBox.Show("Input is incorrect""Error");  
  37.     }  
  38.       
  39. }