Search code examples
c#arraysclasscounterformatexception

Format Exception was unhandled...?


My teacher provided me code to use to create a program, but, when I run it, it gives me 'FormatException was unhandled'. It suggests for me to convert a string to DateTime, but that has nothing to do with the code. I really can't pinpoint where the issue is. I'm using C#, through Microsoft Visual Studio, if that's any help.

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; }
    }        
}

Solution

  • Let's have a look:

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

    you've parsed txtGPA.Text then clear it and try to parse again (since the code is within the for loop). An empty value can't be converted into double and you have the exception thrown.

    Probably, you want to pull all the values from the loop:

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

    please note, that students[counter] is still very suspicious code since counter is not a loop variable (that's i).