Skip to content
Loading
  • Sachin Singh
    0
    If you want to allow only numerics and backspace then the Key_Press event should be
    1. e.Handled = !Char.IsNumber(e.KeyChar) || e.KeyChar == '\b'; 
     Here is the code to check if backspace is pressed
    1. if(e.KeyChar == '\b'){  
    2.   
    3. //backspace was pressed  
    4.   
    5. } 
     
    0
  • Jaimin Shethiya
    0
    Hello Shipa,
    1. private void textBox1_KeyPress(object sender, KeyPressEventArgs e)  
    2. {  
    3. e.Handled = !Char.IsNumber(e.KeyChar) && e.KeyChar != 8; //8 is allow the backspace  
    4. }  
    Thanks
    0
  • Amit Mohanty
    0
    Hey, please check below code.
    1. //1.  allowed only numeric value  ex.10  
    2. private void Number_KeyPress(object sender, KeyPressEventArgs e)  
    3. {  
    4.     //allowed only numeric value  ex.10  
    5.     if (e.KeyChar >= 48 && e.KeyChar <= 57 || e.KeyChar == 8)  
    6.     {  
    7.         e.Handled = false;  
    8.     }  
    9.     else  
    10.     {  
    11.         e.Handled = true;  
    12.     }  
    13. }  
    14.   
    15. //2. allowed numeric and one dot  ex. 10.23  
    16. private void Numeric_KeyPress(object sender, KeyPressEventArgs e)  
    17. {  
    18.     // allowed numeric and one dot  ex. 10.23  
    19.     if (e.KeyChar >= 48 && e.KeyChar <= 57 || e.KeyChar == 8 || e.KeyChar == 46)  
    20.     {  
    21.         e.Handled = false;  
    22.     }  
    23.     else  
    24.     {  
    25.         e.Handled = true;  
    26.     }  
    27.   
    28.     // only allow one decimal point  
    29.     if (e.KeyChar == 46 && (sender as TextBox).Text.IndexOf('.') > -1)  
    30.     {  
    31.         e.Handled = true;  
    32.     }  
    33. }  
    34.   
    35.   
    36. //3. Allow only allow one decimal point,  negative number and backspace  
    37. private void NumberNegitive_KeyPress(object sender, KeyPressEventArgs e)  
    38. {  
    39.     if (e.KeyChar >= 48 && e.KeyChar <= 57 || e.KeyChar == 46 || e.KeyChar == 45)  
    40.     {  
    41.         e.Handled = false;  
    42.     }  
    43.     else  
    44.     {  
    45.         e.Handled = true;  
    46.     }  
    47.   
    48.     // only allow one decimal point  
    49.     if (e.KeyChar == 46 && (sender as TextBox).Text.IndexOf('.') > -1)  
    50.     {  
    51.         e.Handled = true;  
    52.     }  
    53.   
    54.     // allow negative  
    55.     Regex reg = new Regex(@"^-?\d+[.]?\d*$");  
    56.     if (!reg.IsMatch((sender as TextBox).Text.Insert((sender as TextBox).SelectionStart, e.KeyChar.ToString()) + "1"))  
    57.     {  
    58.         e.Handled = true;  
    59.     }  
    60.   
    61.     // allow backspace  
    62.     if (e.KeyChar == 8)  
    63.     {  
    64.         e.Handled = false;  
    65.     }  
    66. } 
    0