0

I want a listbox to display all the students from class M5 etc. but instead it displays one student only.

Another problem is when I randomly select a name from the listbox, the information of the student will be displayed on the right but when I click the student, there's an error nullreferenceexception was unhandled.

Here's is my code:

    private void loadToolStripMenuItem_Click(object sender, EventArgs e)
    {
        openFileDialog1.ShowDialog();
        fileToolStripMenuItem.Text = openFileDialog1.FileName;


        StreamReader sr = new StreamReader(openFileDialog1.FileName);

        string line = "";


            while ((line = sr.ReadLine()) != null)
            {

                string name = "";
                string gender = "";

                char[] selected = line.ToCharArray();

                for (int i = 0; i < selected.Length; i++)
                {
                    if (selected[i] != '(')
                    {
                        name += selected[i];

                    }

                    else if (selected[i] == '(')
                    {
                        gender += selected[i + 1];
                        break;
                    }

                }

                Student student = new Student();

                student.setName(name);
                student.setGender(gender);

                studentListBox.Items.Clear();
                birthdatePicker.Value = DateTime.Now;
                studentlist.addStudent(student);
                studentListBox.Items.Add(student);

        }

        sr.Close();

    private void studentListBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        string name = studentListBox.SelectedItem.ToString();

        Student s = studentlist.findStudent(name);

        s.setName(studentNameTB.Text); <---Error (nullreferenceexception was unhandled)
        s.setGender(genderTB.Text);
        s.setBirthDate(birthdatePicker.Value);
    }
Community
  • 1
  • 1
mosyahri2
  • 7
  • 3
  • For the second part of your question. Show the code of findStudent and show also how the student class overrides the ToString() method to display the student name in the listbox – Steve Jan 23 '16 at 17:40

2 Answers2

3

For the "one student only" problem, remove this line from your while loop and put it before it :

studentListBox.Items.Clear();

The problem is that you are removing all your students each time before adding a new one.

Izuka
  • 2,572
  • 5
  • 29
  • 34
0

Is it possible that studentlist.findStudent(name); returns null? If that's the problem, then you should see your studentlist.findStudent(name) method.

M. Schena
  • 2,039
  • 1
  • 21
  • 29