How can I determine if the Backspace has been pressed in the KeyPress event?

This:

http://msdn.microsoft.com/en-us/library/system.windows.forms.control.keypress.aspx

...indicates that I should have access to e.KeyCode in the KeyPress event, but I don't seem to. I'm trying to allow only 1,2,3, and backspace:

private void textBoxQH1_KeyPress(object sender, KeyPressEventArgs e) {
  if ((e.KeyChar != '1') &&
      (e.KeyChar != '2') &&
      (e.KeyChar != '3') &&
      (e.KeyChar != (Keys.Back))) {
    e.Handled = true; 
  }
}

...but "e." does not show a "KeyCode" value like the example shows, and trying KeyChar with Keys.Back scolds me with, "Operator '!=' cannot be applied to operands of type 'char' and 'System.Windows.Forms.Keys'"

So how can I accomplish this?

Upvotes: 11

Views: 31726

Answers (4)

Lod
Lod

Reputation: 779

I needed to add 0 back after deleting all the textbox content with backspace (if last keystroke is backspace condition is met), while still clearing the textbox upon Keypress and the texbox only contains zero (when first putting input in textbox, with the Form1.cs [Desigh] Properties Text set to 0):

    private void textBox14_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (textBox14.Text == "0")
            textBox14.Clear();

        if (e.KeyChar == ((char)Keys.Back))
        {
            if (textBox14.Text.Length <= 1)
            {
                textBox14.Text = "0";
            }
        }

        if (e.KeyChar >= '0' && e.KeyChar <= '9') return;
        if (e.KeyChar == '+' || e.KeyChar == '-' || e.KeyChar == '.') return;
        if (!Char.IsControl(e.KeyChar))

        e.Handled = true;
    }

Upvotes: 0

ankur goel
ankur goel

Reputation: 76

Try to put a condition like this:

Code :

 if (e.KeyCode == (Keys.Back))
 {
        if(textBox1.Text.Length >=3)
        {
             if (textBox1.Text.Contains("-"))
             {
                 textBox1.Text.Replace("-", "");
             }
        }
 }

Upvotes: 1

jorgehmv
jorgehmv

Reputation: 3713

try comparing e.KeyChar != (char)Keys.Back, you should cast it to char since Keys is an enumeration

see this: KeyPressEventArgs.KeyChar

Upvotes: 25

Neil Barnwell
Neil Barnwell

Reputation: 42165

I'm pretty sure I've only ever solved this by using the KeyDown event instead; it has different event arguments.

Upvotes: 2

Related Questions