int.Parse, Input string was not in a correct format
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.
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;
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.
}
if(!String.IsNullOrEmpty(Textbox1.text))
var number = int.Parse(Textbox1.text);
Or even better:
int number;
int.TryParse(Textbox1.Text, out number);
Try this:
int number;
if (int.TryParse(TextBox1.Text, out number))
{
//Some action if input string is correct
}
If the input is a number or an empty string this will work. It will return zero if the string is empty or else it will return the actual number.
int.Parse("0"+Textbox1.Text)