Search code examples
c#winformskeypresskeydownenter

Using textbox with no button , Enter to execute then Only numbers allowed


when i execute it will run but when i press the enter key the message box still appears

for moneytextbox Keydown

         if (e.KeyCode == Keys.Enter)
         {
            int a, b, c;
            a = int.Parse(money.Text);
            b = int.Parse(bill.Text);
            c = a - b;

            change.Text = c.ToString();
        }

for moneytextboxKeypress

 if (!(Char.IsDigit(e.KeyChar) || (e.KeyChar == (char)Keys.Back)))
 {
      MessageBox.Show("please enter digits only");
      e.Handled = true;
 }

i tried to unblock the enter key in the keypress event

if (!(Char.IsDigit(e.KeyChar) || (e.KeyChar == (char)Keys.Enter))) 
{ 
    MessageBox.Show("please enter digits only"); e.Handled = true; 
} 

but "message box" still appears


Solution

  • You are calling Keypress twice since once you press anything on your keyboard, the keydown event will triggered. Since you press the "keypress", both the keydown and keypress event handler will be triggered. Put everything on keydown event handler to handle all your request:

     if (e.KeyCode == Keys.Enter)
            {
                int a, b, c;
                a = int.Parse(label1.Text);
                b = int.Parse(label2.Text);
                c = a - b;
    
                label3.Text = c.ToString();
                return;
            }
    
            if (!(Char.IsDigit((char)e.KeyData) || (e.KeyData == Keys.Up)))
            {
                MessageBox.Show("please enter digits only");
            }
    

    And remove the moneytextboxKeypress.