Why am I getting a FormatException was unhandled error?

后端 未结 3 800
情话喂你
情话喂你 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...)

    0 讨论(0)
  • 2020-12-12 02:42

    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);
    }
    
    0 讨论(0)
  • 2020-12-12 02:47

    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.
    }
    
    0 讨论(0)
提交回复
热议问题