Re: Only accept number in textbox

Originally Posted by
JonnyPoet
Why not simple use a filter so only numbers can reach the textbox.
You can do it in the keydown event delegate of your texboxes like
Code:
public void TextBox1_ KeyDown(KeyEventArgs e) {
MathSignsOnly(e);
}
private void MathSignsOnly(KeyEventArgs e) {
if (!((e.KeyCode >= Keys.D0 && e.KeyCode <= Keys.D9 && !e.Shift) || (e.KeyCode >= Keys.NumPad0 && e.KeyCode <= Keys.NumPad9) ||
e.KeyCode == Keys.Oemcomma || e.KeyCode == Keys.OemPeriod || e.KeyCode == Keys.Back || e.KeyCode == Keys.Decimal || e.KeyCode == Keys.Delete ||
e.KeyCode == Keys.Enter || e.KeyCode == Keys.Escape || e.KeyCode == Keys.NumLock || e.KeyCode == Keys.Right ||
e.KeyCode == Keys.Left || e.KeyCode == Keys.Home || e.KeyCode == Keys.End)) {
e.SuppressKeyPress = true;
}
}
I'm using such filters together with a decorator. This way I can have different filters for different textboxes. They all get exactly that filter they need.
The above filter allowes unsigned decimal values only but no alphabet letters. This way you can supress everything you want if you want a minus sign simple add it here. If you want keyUp KeyDown, Left, right simple add them to be allowed
Almost perfect one! It can't prevent user typing "459.54-98".
I added lots of source code to prevent this.
Thank you.
The difficulty is that you have no idea how difficult it is.
.Net 3.5/VS 2008