locked
Why dosen't this work? RRS feed

  • Question

  • I'm trying to make it so my textbox can only accept "+", "-" and numbers.

    Here's my code, I'm not sure if I'm autistic or something, but it dosen't give me any error message. It just dosen't work.

            private void onlyNumSym(object sender, KeyPressEventArgs e)
            {
                if (char.IsNumber(e.KeyChar) || e.KeyChar == (char) Keys.Add || e.KeyChar == (char) Keys.Subtract  || e.KeyChar == (char) 8)
                {
    
                }
                else
                {
                    e.Handled = e.KeyChar != (char)Keys.Back;
                    MessageBox.Show("Please enter a valid value.", "Error" );
                }
            }


    Sunday, December 6, 2015 2:30 PM

Answers

  • The normal + and - are not the same as on the numpad. E.g.

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        e.Handled = !(
            e.KeyChar == (char)Keys.Back ||
            char.IsNumber(e.KeyChar) ||
            e.KeyChar == (char)Keys.Execute ||
            e.KeyChar == (char)Keys.Insert
            );
    }
    I would not use the Keys enum at all.

    • Proposed as answer by Magnus (MM8)MVP Sunday, December 6, 2015 4:45 PM
    • Marked as answer by Kristin Xie Tuesday, December 15, 2015 2:11 AM
    Sunday, December 6, 2015 3:03 PM

All replies

  • The normal + and - are not the same as on the numpad. E.g.

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        e.Handled = !(
            e.KeyChar == (char)Keys.Back ||
            char.IsNumber(e.KeyChar) ||
            e.KeyChar == (char)Keys.Execute ||
            e.KeyChar == (char)Keys.Insert
            );
    }
    I would not use the Keys enum at all.

    • Proposed as answer by Magnus (MM8)MVP Sunday, December 6, 2015 4:45 PM
    • Marked as answer by Kristin Xie Tuesday, December 15, 2015 2:11 AM
    Sunday, December 6, 2015 3:03 PM
  • Oh ok, I changed my code a bit and it works great! Also, thank you for the insight!
    Sunday, December 6, 2015 3:43 PM