SHARE
TWEET

input digits, float numbers and negative numbers in TextBox

tolikpunkoff Sep 17th, 2019 103 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. private void txtDigitsWithDotsAndMinus_KeyPress(object sender, KeyPressEventArgs e)
  2. {
  3.     TextBox txt = (TextBox)sender;
  4.     int pos = txt.SelectionStart;
  5.  
  6.     //ввод точки (запятой)
  7.     if ((txt.Text.StartsWith(".")) || (txt.Text.StartsWith(",")))
  8.     {
  9.         // добавление лидирующего ноля
  10.         txt.Text = "0" + txt.Text;
  11.         txt.SelectionStart = pos + 1;
  12.     }
  13.  
  14.     if ((e.KeyChar == '.') || (e.KeyChar == ','))
  15.     {                
  16.         if (txt.Text.Contains(".") || txt.Text.Contains(","))
  17.         {
  18.             e.Handled = true;
  19.             return;
  20.         }                
  21.  
  22.         return;
  23.     }
  24.  
  25.     //ввод минуса
  26.     if (e.KeyChar == '-')
  27.     {                
  28.         if (txt.Text.StartsWith("-"))
  29.         {
  30.             txt.Text = txt.Text.Substring(1);
  31.             txt.SelectionStart = pos - 1;
  32.         }
  33.         else
  34.         {
  35.             txt.Text = "-" + txt.Text;
  36.             txt.SelectionStart = pos + 1;
  37.         }
  38.  
  39.         e.Handled = true;
  40.         return;
  41.     }
  42.  
  43.     //ввод цифр
  44.     if (!(Char.IsDigit(e.KeyChar)))
  45.     {
  46.         if ((e.KeyChar != (char)Keys.Back))
  47.         {
  48.             e.Handled = true;
  49.         }
  50.     }            
  51. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top