29

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.

11 Answers 11

38

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 && ...)
3
  • Just tested it - the comparison against (char)8 does indeed work. Jul 28, 2009 at 3:01
  • 12
    Might be better to use '\b' over (char)8. Jul 11, 2012 at 10:02
  • 12
    @AlexHumphrey I think even better is (char)Keys.Back
    – Antonio
    Sep 23, 2015 at 7:40
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;
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;
            }
        }
3

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;
    }
}
1
  • 4
    The backspace does rise a keypress event
    – Antonio
    Sep 23, 2015 at 7:40
3

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

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

From the documentation:

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

3
  • 5
    In which case the documentation is wrong. I've tested (char)8 from the KeyPress event and it's definitely raised. Jul 28, 2009 at 5:38
  • +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.
    – Mr_Green
    Oct 12, 2012 at 6:58
  • Agreed with Antonio on the prior post and Matt Hamilton above, that despite the doc, the KeyPress event is raised on backspace.
    – David Carr
    Nov 8, 2018 at 23:32
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;
     }
  }
0

This Might Help You

if(Keys.KeyCode==Keys.Back){
   e.Handled =true;
 }
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);
}
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.

-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));
    }
}
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.
    – oɔɯǝɹ
    Feb 8, 2015 at 21:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.