1

I want to write the event handler method button1_Click to calculate whether student’s Grade is “PASS” or “FAIL”. The student passes the course if the total score is greater than or equal to 50. The total score is Midterm(textbox1) + Final(textbox2) scores. However, teacher can give student Extra Credit(checkbox1) which is worth 10 points. The result will present in the textBox3

Here's my code:

private void button1_Click(object sender, EventArgs e)
        {

            int midtermInt = int.Parse(textBox1.Text);


            int finalInt = int.Parse(textBox2.Text);


            if (checkBox1.Checked)
            {
                if ((midtermInt + finalInt) + 10 >= 50)
                {
                    grade.Text = "PASS";
                }
                else if ((midtermInt + finalInt) + 10 < 50)
                {
                    grade.Text = "FAIL";
                }
            }
            else if (!checkBox1.Checked)
            {
                if ((midtermInt + finalInt) >= 50)
                {
                    grade.Text = "PASS";
                }
                else if ((midtermInt + finalInt) < 50)
                {
                    grade.Text = "FAIL";
                }
            }

When I run it, it says "Inut string was not in a correct format.. :( I'm very new to C# please advise me if my code is wrong anywhere

The input will only be integers never texts..

4

3 回答 3

1

If you type non-numeric characters in your textbox and try to parse the text, it will throw you this exception. Try trimming the input and definitely consider adding UI validation to your forms.

于 2012-08-13T10:26:33.053 回答
1

您应该使用 int.TryParse insted int.Parse,它检查指定的字符串格式是否正确。您的代码可能如下所示:

int midtermInt;
if (!int.TryParse(textBox1.Text, out midtermInt))
{
    labelError.Text = "Icorrect value in field 'textBox1'".
    return;
}
于 2012-08-13T10:26:47.793 回答
0

You can add checking, if text in text box is in correct format in TextChanged event:

private void textBox_TextChanged(object sender, EventArgs e)
{
   int val;
   if (textBox.Text.Length == 0 || !int.TryParse(textBox.Text, out val))
      tsPassingScore.Text = "0";
}

And in your click you can check if there is number in textBox again with int.TryParse

Also you can improve your code: If final summ is not bigger then 50 - it is automatically smaller! And it would be more readable, if you introduce extra variable - for teachers extra credit:

int extraCredit = checkBox1.Checked ? 10 : 0;
int finalScore = midtermInt + finalInt + extraCredit;
if (finalScore >= 50)
  grade.Text = "PASS";
else
  grade.Text = "FAIL";
于 2012-08-13T10:25:08.730 回答