Leinad
Leinad

Reputation: 111

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?

Upvotes: 1

Views: 196

Answers (4)

Dharmesh Hadiyal
Dharmesh Hadiyal

Reputation: 729

Also this condition it's working

if (e.KeyChar >= 48 && e.KeyChar <= 57)
{
}
else
{
       e.Handled = true;
}

Upvotes: 0

Berkay Yaylacı
Berkay Yaylacı

Reputation: 4513

Try this,

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

Hope helps,

Upvotes: 1

M. Wiśnicki
M. Wiśnicki

Reputation: 6203

You can cast keys like this and compare.(backspace)

if( e.KeyChar == (char)Keys.Back)
{
}

Upvotes: 0

Dharmesh Hadiyal
Dharmesh Hadiyal

Reputation: 729

Try this condition to check backspace click or not

if (e.KeyCode == Keys.Back)
    {
        e.SuppressKeyPress = true;
    }

Upvotes: 0

Related Questions