I have created a program, and a extensive test of it, I\'m getting a error that says \"FormatException was unhandled, Input string was not in a correct format\". The problem
Well, look at these lines:
int minsEntered = int.Parse(txtMins.Text);
int secsEntered = int.Parse(txtSecs.Text);
What do you expect those to return when the text boxes are blank?
Simply don't call int.Parse
for empty textboxes. For example:
int minsEntered = txtMins.Text == "" ? 0 : int.Parse(txtMins.Text);
// Ditto for seconds
Of course, this will still go bang if you enter something non-numeric. You should probably be using int.TryParse
instead:
int minsEntered;
int.TryParse(txtMins.Text, out minsEntered);
Here I'm ignoring the result of TryParse
, and it will leave minsEntered
as 0 anyway - but if you wanted a different default, you'd use something like:
int minsEntered;
if (!int.TryParse(txtMins.Text, out minsEntered))
{
minsEntered = 5; // Default on parsing failure
}
(Or you can show an error message in that case...)
The problem occurs when I leave either of the text boxes blank
That's the issue. You are using int.Parse
on an empty string. An empty string is not a valid integer representation and the parse fails.
You can test for the value in the textbox and default to something reasonable instead:
int minsEntered = 0;
int secsEntered = 0;
if(!string.IsNullOrWhitespace(textMins.Text))
{
minsEntered = int.Parse(txtMins.Text);
}
if(!string.IsNullOrWhitespace(txtSecs.Text))
{
secsEntered = int.Parse(txtSecs.Text);
}
You could use int.TryParse, which returns a bool to indicate whether the text was parsed successfully:
int minsEntered = 0;
if (int.TryParse(txtMins.Text, out minsEntered))
{
// txtMins.Text is a valid integer.
}