Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

int.Parse, Input string was not in a correct format

Tags:

c#

How would I parse an empty string? int.Parse(Textbox1.text) gives me an error:

Input string was not in a correct format.
System.FormatException: Input string was not in a correct format.

If the text is empty (Textbox1.text = ''), it throws this error. I understand this error but not sure how to correct this.

like image 948
user575219 Avatar asked Feb 21 '12 04:02

user575219


People also ask

What is parse method in C#?

Parse(String) Method is used to convert the string representation of a number to its 32-bit signed integer equivalent. Syntax: public static int Parse (string str); Here, str is a string that contains a number to convert. The format of str will be [optional white space][optional sign]digits[optional white space].

What is an input string?

InputString returns what it reads as a string, without evaluation. The operation of InputString may vary from one computer system to another. When a Wolfram System front end is used, InputString typically works through a dialog box. When no front end is used, InputString reads from standard input.


3 Answers

If you're looking to default to 0 on an empty textbox (and throw an exception on poorly formatted input):

int i = string.IsNullOrEmpty(Textbox1.Text) ? 0 : int.Parse(Textbox1.Text);

If you're looking to default to 0 with any poorly formatted input:

int i;
if (!int.TryParse(Textbox1.Text, out i)) i = 0;
like image 78
userx Avatar answered Oct 20 '22 06:10

userx


Well, what do you want the result to be? If you just want to validate input, use int.TryParse instead:

int result;

if (int.TryParse(Textbox1.Text, out result)) {
    // Valid input, do something with it.
} else {
    // Not a number, do something else with it.
}
like image 25
Ry- Avatar answered Oct 20 '22 08:10

Ry-


if(!String.IsNullOrEmpty(Textbox1.text))
    var number = int.Parse(Textbox1.text);

Or even better:

int number;

int.TryParse(Textbox1.Text, out number);
like image 7
Alex Avatar answered Oct 20 '22 07:10

Alex