Question

    private void btnAddStudent_Click(object sender, EventArgs e)
    {
        student[counter] = new Student(txtStudentName.Text, txtStudentSurname.Text,     int.Parse(txtExamMark.Text), counter);
        counter++;

    }

    private void btnAverage_Click(object sender, EventArgs e)
    {

        for (int i = counter; i <= counter; i++)
            MessageBox.Show("" + student[i].Average);
    }

My program is giving me the error:

Object reference not set to an instance of an object.

I only want the loop to run once to only display the last calculated average. If i do this: ie: change int i = counter to i = 0

    private void btnAverage_Click(object sender, EventArgs e)
    {

        for (int i = 0; i < counter; i++)
            MessageBox.Show("" + student[i].Average);
    }

Then my program works but it displays the messagebox as many times depending on the amount of students i entered, with the last value being the correct average.

I used a class called Student to calculate the average. That is not the problem however, because the correct average is being displayed.

What can I do to fix this error?

Was it helpful?

Solution

Firstly, you do not appear to need a loop since counter is going from counter to counter.

Secondly, I suspect you have an out-by-one error.

What happens if you try this?

private void btnAverage_Click(object sender, EventArgs e)
{
    if (counter > 0)
        MessageBox.Show("" + student[counter-1].Average);
}

OTHER TIPS

Your problem is that student[counter] is null, while student[0] isn't, so I guess that your counter is not properly aligned with your student array.

Try

if (student.Length > 0)
{
    MessageBox.Show("" + student[student.Length - 1].Average)
}

without the loop - that will just show the last average in the array.

I believe the problem is because you are trying to access an item in the array/collection that has no instance (Why you receive the error). Setting counter to 0 works because student[0] has an instance of Student.

If you want to only get one item, you don't need a loop, you can access student[i] directly by passing in the index of the array, i.e. 0.

MessageBox.Show("" + student[0].Average);

A less error-prone approach would be to use a List<T> instead of an array:

List<Student> students = new List<Student>();
private void btnAddStudent_Click(object sender, EventArgs e)
{
    students.Add(Student(txtStudentName.Text, txtStudentSurname.Text,
                 int.Parse(txtExamMark.Text), counter);
    counter++;
}

private void btnAverage_Click(object sender, EventArgs e)
{
    if(students.Any())
    {
        MessageBox.Show("" + students.Last().Average);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top