Leinad Leinad - 2 months ago 10
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

Try this,

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

Hope helps,

Comments