How can I accept the backspace key in the keypress event?
Asked Answered
E

11

30

This is my code:

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

It allows me to enter letters, numbers and spaces but it doesn't allow me to do backspace. Please help me.

Engvall answered 28/7, 2009 at 2:49 Comment(0)
U
40

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 && ...)
Uriel answered 28/7, 2009 at 2:59 Comment(3)
Just tested it - the comparison against (char)8 does indeed work.Uriel
Might be better to use '\b' over (char)8.Campbellbannerman
@AlexHumphrey I think even better is (char)Keys.BackShelley
M
20

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;
Microeconomics answered 22/9, 2012 at 0:45 Comment(0)
T
7

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;
            }
        }
Taeniacide answered 21/11, 2016 at 23:17 Comment(0)
L
4

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;
    }
}
Lx answered 5/8, 2013 at 16:7 Comment(1)
The backspace does rise a keypress eventShelley
C
3

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

e.KeyChar == ((char)Keys.Back)
Correna answered 21/2, 2020 at 17:23 Comment(0)
Z
1

From the documentation:

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

Zingaro answered 28/7, 2009 at 3:17 Comment(3)
In which case the documentation is wrong. I've tested (char)8 from the KeyPress event and it's definitely raised.Uriel
+1 I am fully satisfied with Ed S. why using type casting when we have key up and key down events. In normal cases we should avoid type casting. we should use type casting when we dont have any other alternatives.Civics
Agreed with Antonio on the prior post and Matt Hamilton above, that despite the doc, the KeyPress event is raised on backspace.Teflon
F
0
private void KeyPressNameSurname(object sender, KeyPressEventArgs e)
 {
     if (char.IsPunctuation(e.KeyChar) || char.IsSymbol(e.KeyChar) || char.IsDigit(e.KeyChar) )
     {
        e.Handled = true;
        myTextBox.Text = "Not Valid";
        myTextBox.Visible = true;
     }
     else
     {
        myTextBox.Visible = false;
     }
  }
Ferrochromium answered 11/8, 2015 at 5:33 Comment(0)
P
0

This Might Help You

if(Keys.KeyCode==Keys.Back){
   e.Handled =true;
 }
Pentecost answered 25/3, 2021 at 10:0 Comment(0)
R
0

To Allow only numbers and backspace

private void txt_KeyPress(object sender, KeyPressEventArgs e)
{
   e.Handled = !(char.IsDigit(e.KeyChar) || e.KeyChar == (char)8);
}
Ryannryazan answered 5/4, 2022 at 18:40 Comment(0)
H
0

While this is a very OLD question some folks may find that the code does not work.
I tried to use this code to capture a BACKSPACE key press inside a RichTextBox
That is using public void rtbInfo_TextChanged(Object sender, EventArgs e)
And Yes without adding this line code the BACKSPACE keypress was never detected

public frmRTB()
    {
        InitializeComponent();
        rtbInfo.KeyPress += rtbInfo_KeyPress;
    }

It seems you need to register the component or shall we say tool.

Hearing answered 7/2, 2023 at 0:11 Comment(0)
B
-1
private void Keypressusername(object sender, KeyPressEventArgs e)
{
    e.Handled = !(char.IsLetter(e.KeyChar));
    if (char.IsControl(e.KeyChar))
    {
        e.Handled = !(char.IsControl(e.KeyChar));
    }
    if (char.IsWhiteSpace(e.KeyChar))
    {
        e.Handled = !(char.IsWhiteSpace(e.KeyChar));
    }
}
Borreri answered 8/2, 2015 at 21:21 Comment(1)
While this code sample may possibly answer the question, it would be preferable to include some essential explanation to your answer. As it stands now this answer adds little to no value for future readers.Quinte

© 2022 - 2024 — McMap. All rights reserved.