Wednesday, September 09, 2009
Numeric only , windows programing , C#.Net
9:42 PM |
Posted by
Sheen |
Edit Post
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()));
}
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()));
}
Subscribe to:
Post Comments (Atom)
Blog Archive
Important Blogs
-
-
Git Workflow For Enterprise development6 years ago
-
-
Watch Live Cricket Online Free14 years ago
-
-
-
4 comments:
e.Handled = e.KeyChar < '0' || e.KeyChar > '9';
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.
cool man .. but careful, .,1.2.3.45.. 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.
Post a Comment