Why am I getting a FormatException was unhandled error?

…衆ロ難τιáo~ 提交于 2019-11-28 14:11:47

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.
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!