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

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;

Leave a Comment