Hi all, How can I convert the text in a textbox to an integer? Can I use something like this?: [COLOR=Blue] [/COLOR][COLOR=Blue]int[/COLOR] Integer; Integer = Convert.ToInt32(textBox1.Text); Integer = [COLOR=Blue]int[/COLOR].Parse(textBox1.Text); Code (markup): And to menage not expected values (like char o string) is correct using try{} and catch{}? Thanks to all
You can test for the length of the string and not convert if the length is 0. (A string with just char 0 is 0 length.) You could use a try/catch block, but that generates more code than just a simple length test. (The "value" of non-numeric text will be 0.)
With the lenght I can control if the string is empty (0) or not (<0), but I can't control which are the types of data in input (int,char) and I can't menage the error.
You can validate both Windows Forms and ASP.Net controls input values. If you just want to check if a string contains an integer value here is a MSDN How-to article:How to: Determine Whether a String Represents a Numeric Value (C# Programming Guide): http://msdn.microsoft.com/en-us/library/bb384043.aspx Here is the example from the article: int i = 0; string s = "108"; bool result = int.TryParse(s, out i); //i now = 108 Code (markup):
Try/catch is indeed the way to handle it for text values that do not fit -- what you want to intercept is formatException. See the example on the MSDN page for toInt32: http://msdn.microsoft.com/en-us/library/sf1aw27b.aspx or parse: http://msdn.microsoft.com/en-us/library/b3h1hf19.aspx I would use toInt32 so you can dictate the result size. try { int Integer; Integer = Convert.ToInt32(textBox1.Text); // do whatever it is your doing with the integer here } catch (FormatException) { // resend form with error as it's got a non-integer value } Code (markup):