Advertisement
tolikpunkoff

input digits, float numbers and negative numbers in TextBox

Sep 17th, 2019
916
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.24 KB | None | 0 0
  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. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement