-1

Hie i have a code that get the file StudentMarks.dat and outputs all studentID, assessment , marksachieved, maxMarks. However i am able to split all the values but unable to add them to my list and throws me null exception. please help. My code is as follows:

struct StudentGrade
{
    public string StudentID { get; set; }
    public string AssessmentID { get; set; }
    public string MaxGrade { get; set; }
    public string GradeAchieved { get; set; }
}

private List<StudentGrade> _studentGrade;      
private void loadItemsFromFiles()
{
    string record = string.Empty;
    string filePath = "StudentMarks.dat";

    FileStream stream = new FileStream(filePath,FileMode.Open);
    StreamReader reader = new StreamReader(stream);

    dgvGrades.Columns.Add("StudentID", "Student Id");
    dgvGrades.Columns.Add("Assessment", "Assessment");
    dgvGrades.Columns.Add("MarksAchieved", "Marks Achieved");
    dgvGrades.Columns.Add("MaxMarks", "Max Marks");

    try
    {

        while ((record = reader.ReadLine()) != null)
        {
            string[] field = record.Split(',');
            StudentGrade grade = new StudentGrade()
            {
                StudentID =field[0].ToString(),
                AssessmentID = field[1].ToString(),
                MaxGrade = field[2].ToString(),
                GradeAchieved = field[3].ToString()
            };
            _studentGrade.Add(grade);

        }
    }
    catch (IOException exception)
    {
        throw exception;
    }
    finally
    {
        if (reader != null)
        {
            reader.Close();
        }
    }

}
Hamid Pourjam
  • 20,441
  • 9
  • 58
  • 74

2 Answers2

1

You have not initialized your list and it is null so you get the exception.

private List<StudentGrade> _studentGrade = new List<StudentGrade>();

When you declare a class variable in C# it gets the default value of it's type. For example int default value is 0 and bool default value is 'false'. All reference types default valu is 'null'. So when you use them without initializing them you get NullReferenceException.

Hamid Pourjam
  • 20,441
  • 9
  • 58
  • 74
1

You need to initialize your collection before using

private List<StudentGrade> _studentGrade = new List<StudentGrade>();
Nitin
  • 18,344
  • 2
  • 36
  • 53