I am getting this error and I have absolutely no idea how to get rid of it. I allocated the array but cant seem to get it initialized correctly. I allocated the array on line 13 NullReference error. I read about it but in this case I have no idea what I'm doing wrong.
I have the following code.
namespace A4
{
public partial class frmAddStudent : Form
{
public frmAddStudent()
{
InitializeComponent();
}
// Declare variables to be used by both event handlers
int CountStudents = 0;
double Average = 0;
Student[] ClassList = new Student[50];
private void btnAdd_Click(object sender, EventArgs e)
{
// Create new student and assign name etc provided by user
Student _Student = new Student();
_Student.Name = txtName.Text;
_Student.Surname = txtSurname.Text;
_Student.Age = Convert.ToInt32(txtAge.Text);
_Student.ITMark = Convert.ToInt32(txtIT.Text);
_Student.MathMark = Convert.ToInt32(txtEng.Text);
_Student.EngMark = Convert.ToInt32(txtMath.Text);
// Use the hasPassed method to display an appropriate message after the
// student has been added
MessageBox.Show("Student added.");
// Increase counter and display how many students added so far
CountStudents++;
Average = Convert.ToInt32(txtIT.Text) + Convert.ToInt32(txtEng.Text) + Convert.ToInt32(txtMath.Text);
_Student.AverageMark = Average / 3;
//Display Student's properties
richTextBox1.Text += ("Student: " + Convert.ToString(CountStudents) +
"\nName: " + _Student.Name +
"\nSurname: " + _Student.Surname +
"\nAge: " + _Student.Age +
"\nStudent Average: " + Convert.ToString(_Student.AverageMark) + "\n" + "\n");
//Add the newly added student to the ClassList array
ClassList[CountStudents - 1] = _Student;
//Clear the list
txtSurname.Clear();
txtName.Clear();
txtAge.Clear();
txtIT.Value = 0;
txtEng.Value = 0;
txtMath.Value = 0;
txtName.Focus();
}
private void displayAll_Click(object sender, EventArgs e)
{
richTextBox1.Clear();
for (int j = 0; j < ClassList.Count(); j++)
{
richTextBox1.Text += ("Student: " + Convert.ToString(j) +
"\nName: " + ClassList[j].Name +
"\nSurname: " + ClassList[j].Surname +
"\nAge: " + ClassList[j].Age +
"\nStudent Average: " + Convert.ToString(ClassList[j].AverageMark) +
"\n" + "\n");
}
//MessageBox.Show("Display all students.");
}
}
}