This is my code:
private void txtAdd_KeyPress(object sender, KeyPressEventArgs e)
{
if (!(char.IsLetter(e.KeyChar)) && !(char.IsNumber(e.KeyChar)
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;
}
}
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 && ...)
From the documentation:
The KeyPress event is not raised by noncharacter keys; however, the noncharacter keys do raise the KeyDown and KeyUp events.
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;
}
}
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));
}
}
for your problem try this its work for when backspace key pressed
e.KeyChar == ((char)Keys.Back)