Wednesday, September 09, 2009

Numeric only , windows programing , C#.Net

If you want to restrict a text box, to enter only numeric values.
Just do the following in the KeyPress event.

private void txtOpenCount_KeyPress(object sender, KeyPressEventArgs e)
string str = "\b0123456789";
e.Handled = !(str.Contains(e.KeyChar.ToString()));


S. said...
This comment has been removed by the author.
S. said...

e.Handled = e.KeyChar < '0' || e.KeyChar > '9';

shiran said...

Yes this is anotherway and easy when you have to restrict only 0 to 9, but the one in original post is esy when you have to allow some other values for example

. (decimal point)
, (comma)

string str = "\b0123456789.,";

you just have to include those 2 characters in to your string as above. but in your case we have to keep on adding e.KeyChar = 'whatever'. Thoughts always appriciated.

S. said...

cool man .. but careful, ., is not numeric !

If u wanna include decimals, easiest is:

e.Handled = !Regex.IsMatch(txtOpenCount.Text + e.KeyChar, @"^\d+(\.(\d{1,2})?)?$");

Replace '2' above if precision > 2

However u might have to account for situ's like "123." or "1." Take care of this on validate. Also allow backspace key to allow editing.

If u really wanna dance, derive ur own numeric class from TextBox and add these lil things into it so u can drop it in any project. As for commas, they are just display sugar .. forget about them for form inputs.

My Achievements

Member of

Blog Archive