3

I have the following code to only allow letters in the text box:

private void TextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
  Char pressedKey = e.KeyChar;
  if (Char.IsLetter(pressedKey))
 {
// Allow input.
e.Handled = false
}
  else
e.Handled = true;
}
}

How can I allow the backspace key to work because, it doesnt let me to delete characters after typed

user2154328
  • 43
  • 1
  • 2
  • 9
  • does this help? http://stackoverflow.com/questions/1191698/how-can-i-accept-the-backspace-key-in-the-keypress-event – bas Mar 10 '13 at 20:33
  • 1
    maybe that was too vague, using `Char.IsControl(e.KeyChar)` allows you to enter backspace and move the carret (I guess you also want to allow your users with moving the cursor). If you really only want to allow backspace, according to that post you need `if (e.KeyChar == (char)8)` – bas Mar 10 '13 at 20:36

2 Answers2

3

You can check if the key pressed is a Control character using Char.IsControl(...), like this:

private void TextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!Char.IsLetter(e.KeyChar) && !Char.IsControl(e.KeyChar))
        e.Handled = true;
}

If you specifically need to check only chars + Delete, use this:

private void TextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!Char.IsLetter(e.KeyChar) && e.KeyChar != (char)Keys.Back)
        e.Handled = true;
}
Jakob Möllås
  • 4,239
  • 3
  • 33
  • 61
0

This is for those using VB.net. There's a weird conversion I'd never come across that took me a while to figure out.

This allows only numbers, letters, backspace and space.

Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress
    e.Handled = e.KeyChar <> ChrW(Keys.Back) And Not Char.IsLetter(e.KeyChar) And Not Char.IsDigit(e.KeyChar) And Not Char.IsSeparator(e.KeyChar)
End Sub
KidBilly
  • 3,408
  • 1
  • 26
  • 40