我想要一個列表框來顯示所有來自班級M5等的學生,但它只顯示一個學生。列表框顯示所有學生
另一個問題是,當我從列表框中隨機選擇一個名稱時,學生的信息將顯示在右側,但是當我單擊學生時,出現錯誤nullreferenceexception未處理。
這裏是我的代碼:
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);
}
對於問題的第二部分。顯示findStudent的代碼並顯示學生類如何覆蓋ToString()方法以在列表框中顯示學生名稱 – Steve