Strings to ints
-
I have a text box to get info off the user. It should be an int but i cant be sure so i must validate it first. How do I tell if a string is an int? I know i could do Convert.toInt.... and put it in a try catch but is there another way? Thanks in advance
-
I have a text box to get info off the user. It should be an int but i cant be sure so i must validate it first. How do I tell if a string is an int? I know i could do Convert.toInt.... and put it in a try catch but is there another way? Thanks in advance
try int.TryParse()[^] Look up the overloads too, because it intially expects an int with no formatting whatsoever, but using system.globalization.numberstyle.* you can have it automaticlly handle commas, currency symbols, etc.
-
I have a text box to get info off the user. It should be an int but i cant be sure so i must validate it first. How do I tell if a string is an int? I know i could do Convert.toInt.... and put it in a try catch but is there another way? Thanks in advance
-
I have a text box to get info off the user. It should be an int but i cant be sure so i must validate it first. How do I tell if a string is an int? I know i could do Convert.toInt.... and put it in a try catch but is there another way? Thanks in advance
You could use a regular expression to test the string to see that all characters are numeric. Somthing like:
private static Regex _isNumber = new Regex(@"^\d+$"); public static bool IsInteger(string theValue) { Match m = _isNumber.Match(theValue); return m.Success; }
*not tested
Louis * google is your friend * -- modified at 16:36 Wednesday 19th April, 2006
-
I have a text box to get info off the user. It should be an int but i cant be sure so i must validate it first. How do I tell if a string is an int? I know i could do Convert.toInt.... and put it in a try catch but is there another way? Thanks in advance
You can also try to capture the KeyPress event on the text box and check the user input. void TextBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e) { if(!Char.IsDigit(e.KeyChar) && e.KeyChar != (char)8) { e.Handled = true; } else { e.Handled = false; } } (char) 8 is the backspace key...so the user can actually delete the entry as well !