Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I accept the backspace key in the keypress event?

Tags:

c#

keypress

People also ask

How do I put Backspace in keypress?

You can capture a backspace key on the onkeydown event. Once you get the key of the pressed button, then match it with the Backspace key code. A Backspace key keycode it 8.

How do you check Backspace in keypress?

Try keydown instead of keypress . The problem with backspace probably is, that the browser will navigate back on keyup and thus your page will not see the keypress event. It also seems that, for key events in inputs, the character doesn't appear in the field until the keyup event is fired.


I like to use !Char.IsControl(e.KeyChar) so that all the "control" characters like the backspace key and clipboard keyboard shortcuts are exempted.

If you just want to check for backspace, you can probably get away with:

if (e.KeyChar == (char)8 && ...)

I use the two following segments alot:

This one for restricting a textbox to integer only, but allowing control keys:

if (Char.IsDigit(e.KeyChar)) return;
if (Char.IsControl(e.KeyChar)) return;
e.Handled = true;

This one for restricing a textbox to doubles, allowing one '.' only, and allowing control keys:

if (Char.IsDigit(e.KeyChar)) return;
if (Char.IsControl(e.KeyChar)) return;
if ((e.KeyChar == '.') && ((sender as TextBox).Text.Contains('.') == false)) return;
if ((e.KeyChar == '.') && ((sender as TextBox).SelectionLength == (sender as TextBox).TextLength)) return;
e.Handled = true;

You have to add !(char.IsControl(e.KeyChar)) in you sentence and that's it.

private void txtNombre_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(char.IsLetter(e.KeyChar)) && !(char.IsNumber(e.KeyChar)) && !(char.IsControl(e.KeyChar)) && !(char.IsWhiteSpace(e.KeyChar)))
            {
                e.Handled = true;
            }
        }

The backspace key does not raised by KeyPress event. So you need to catch it in KeyDown or KeyUp events and set SuppressKeyPress property is true to prevent backspace key change your text in textbox:

private void txtAdd_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Back)
    {
        e.SuppressKeyPress = true;
    }
}

for your problem try this its work for when backspace key pressed

e.KeyChar == ((char)Keys.Back)

From the documentation:

The KeyPress event is not raised by noncharacter keys; however, the noncharacter keys do raise the KeyDown and KeyUp events.