格式异常未处理...?

Format Exception was unhandled...?

我的老师为我提供了用于创建程序的代码,但是,当我 运行 它时,它给了我 'FormatException was unhandled'。它建议我将字符串转换为 DateTime,但这与代码无关。我真的无法确定问题出在哪里。我正在通过 Microsoft Visual Studio 使用 C#,如果有帮助的话。

private void btnAdd_Click(object sender, EventArgs e)
{
    student[] students = new student[5];
    int i;
    for (i = 0; i < 5; i++)
    {
        students[i] = new student();
        try
        {
            int counter = 0; //array index counter
            students[counter].personName = txtName.Text;
            students[counter].personGPA = Convert.ToDouble(txtGPA.Text);

            txtDisplay.Text += "Name: " + students[counter].Name + "\r\n GPA: " + students[counter].GPA.ToString();
            counter++; //increment the array index counter by 1
            txtName.Text = string.Empty;
            txtGPA.Text = string.Empty;
            txtName.Focus();
        } //end of code for the try block
        catch (ArgumentException) //GPA is out of range
        {
            MessageBox.Show("Please enter a proper GPA");
        }
        catch (IndexOutOfRangeException) //array is full
        {
            MessageBox.Show("There are already 5 students.");
        }
    }
}

class student
{
    public String personName;
    public Double personGPA;

    public string Name
    {
       // get;
        //set; 
        get { return personName; }
        set { personName = value; }
    }

    public double GPA
    {
        //get;
        //set;
        get {return personGPA; }
        set { personGPA = value; }
    }        
}

一起来看看:

 for (...) {
   ...
   students[counter].personGPA = Convert.ToDouble(txtGPA.Text);
   ...
   txtGPA.Text = string.Empty;

你已经解析 txtGPA.Text然后清除它并尝试再次解析(因为代码在 for 循环 中)。 值无法转换为 double 并且抛出异常。

您可能想要从循环中提取所有值:

 double gpa = Convert.ToDouble(txtGPA.Text); 
 txtGPA.Text = String.Empty;

 for (...) {
   ... 
   students[counter].personGPA = gpa;

请注意,students[counter] 仍然是非常可疑的代码,因为 counter 不是 循环变量 (即 i)。