Allow backspace

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

In a text box I want to allow only numbers and backspace.

Currently the code I have only allows numbers. How do I also allow backspace?

if (!Char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
 
Put a breakpoint there and see what character code you get when you hit
backspace. It should be one of the control characters.
 
Mike L said:
In a text box I want to allow only numbers and backspace.

Currently the code I have only allows numbers. How do I also allow
backspace?

if (!Char.IsDigit(e.KeyChar))
{
e.Handled = true;
}

if (!Char.IsDigit(e.KeyChar) && e.KeyCode != Keys.Back) {
e.Handled = True;
}

HTH,
Mythran
 
Hi Mike,

I usually use Char.IsControl as this allows for cut and paste as well.

if (!Char.IsDigit(e.KeyChar) || !Char.IsControl(e.KeyChar))
e.Handled = true;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top