mosyahri2
mosyahri2

Reputation: 1

Listbox display error :(

Supposedly the listbox show the list of student's name and gender but instead its display Assignment2.Student. Pls help fix my problem :(

    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);
        s.setGender(genderTB.Text);
        s.setBirthDate(birthdatePicker.Value);
    }

Upvotes: 0

Views: 110

Answers (2)

COB RCE
COB RCE

Reputation: 1

you can optimize your code like follow

string[] students = File.ReadAllLines(openFileDialog1.FileName);
foreach (string student in students)
{
    string[] split = student.Split('(');
    StudentList.Add(new Student() { Name = split[0], Gender = split[1][0].ToString() });
}
listBox1.Items.Clear();
listBox1.Items.AddRange(StudentList.ToArray());

and for display problem I would advice to override ToString() function

public override string ToString()
{
    return string.Format("{0} / {1} ", Name, Gender);
}

Upvotes: 0

Izuka
Izuka

Reputation: 2612

You have to override the ToString function for your Student class. The ListBox will then use this method to show the information you want about each one of your student :

public override String ToString()
{
    return name + " " + gender;
}

If you don't override it, the ToString method will just return the type of your object, here Assignment2.Student.

Upvotes: 2

Related Questions