Why am I getting a FormatException was unhandled error?

后端 未结 3 816
情话喂你
情话喂你 2020-12-12 01:51

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

3条回答
  •  隐瞒了意图╮
    2020-12-12 02:42

    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...)

提交回复
热议问题