1

I have an application which makes a user input his/her details about a course ID, NAME, Module1- Module4 marks. I've a button Add and a button for Edit. Whenever a user inputs his/her details, everything is stored in a list named allStudent, variables are stored in a struct and the module marks are stored as array Marks, also the ID is added to a listbox which the user can select and edit. My problem is when i click Edit i get an error "System.NullReferenceException: 'Object reference not set to an instance of an object.' " It highlights S.Marks[0] = int.Parse(txtM1.Text); in btnEdit_Click

struct Student
    {
        public int ID;
        public string Name;
        public int[] Marks;
    }

    List<Student> allStudents = new List<Student>();

    private void btnAdd_Click(object sender, EventArgs e)
    {
        Student S = new Student();
        S.Marks = new int[4];

        S.ID = int.Parse(txtId.Text);
        S.Name = txtName.Text;

        S.Marks[0] = int.Parse(txtM1.Text);
        S.Marks[1] = int.Parse(txtM2.Text);
        S.Marks[2] = int.Parse(txtM3.Text);
        S.Marks[3] = int.Parse(txtM4.Text);

        allStudents.Add(S);

        lstBox.Items.Add(S.ID);
    }

    private void btnEdit_Click(object sender, EventArgs e)
    {
        Student S = new Student();

        S.ID = int.Parse(txtId.Text);
        S.Name = txtName.Text;

        S.Marks[0] = int.Parse(txtM1.Text);
        S.Marks[1] = int.Parse(txtM2.Text);
        S.Marks[2] = int.Parse(txtM3.Text);
        S.Marks[3] = int.Parse(txtM4.Text);

        allStudents[lstBox.SelectedIndex] = S;
    }
Cat_img.jpeg
  • 585
  • 4
  • 8

1 Answers1

5

I think you forgot initialize your Marks array after creating Student object

S.Marks = new int[4];
Eugene Chybisov
  • 1,634
  • 2
  • 23
  • 32