Leinad Leinad - 1 year ago 97
C# Question

Backspace key don't works with KeyPress function

I have a TextBox, that only accepts numbers. It works, but the backspace key has no functionality.

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
int isNumber = 0;
e.Handled = !int.TryParse(e.KeyChar.ToString(), out isNumber);

What is wrong?

Answer Source

Try this,

e.Handled = !int.TryParse(e.KeyChar != (char)Keys.Back ? e.KeyChar.ToString() : "0", out isNumber);

Hope helps,

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download