Search code examples
c#decimalkeypress

KeyPress Event gives wrong value


I made a KeyPress Event and want to allow only Double values (or just digits and comma) so I tried this:

 e.Handled = !(char.IsNumber(e.KeyChar) || e.KeyChar == (char)Keys.Back || e.KeyChar == (char)Keys.Decimal);

But somehow he's got problems with the "Decimal". I'm using a german keyboard and when I try to enter the comma, he does nothing. When I press the "n" key he writes the letter. What is wrong here and how to solve that?


Solution

  • you can restrict the input using keyPress event like so:

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
       char c= e.KeyChar;
       if (!char.IsDigit(c) && !char.IsControl(c))
       {
          e.Handled = true;
        }
    }
    

    if we want to extend our restriction condition to accept a certain character (for example ,)

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
      char c= e.KeyChar;
      if (!char.IsDigit(c) && !char.IsControl(c) && c!=',')
      {
        e.Handled = true;
      }
    }
    

    To avoid having multiple comma like 222,34545,454 we can do this work around:

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
      char c= e.KeyChar;
      bool comma= textBox1.Text.Contains(','); //true in case comma already inserted
    
      // accepts only digits, controls and comma
      if (!char.IsDigit(c) && !char.IsControl(c) && c!=',')
      {
        e.Handled = true;
        return;
      }
    
    
      // whenever a comma is inserted we check if we already have one
      if (c == ',' && comma)
      {
        e.Handled = true;
      }
    }