我选择的列表框出现问题

时间:2016-01-24 01:17:25

标签: c# listbox

基本上,我想在列表框中选择ABDUL SIDDIQ BIN MOHD YUSSAINI(M),然后学生的信息将显示在右侧。

正确输出

  

学生姓名:ABDUL SIDDIQ BIN MOHD YUSSAINI

     

性别:(M)

但是当我选择abdul时它会显示:

  

学生姓名:ABDUL SIDDIQ BIN MOHD YUSSAINI(M)

     

性别:ABDUL SIDDIQ BIN MOHD YUSSAINI

这是我的编码:

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);

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


  }

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

   Student s = studentlist.findStudent(name);

   if (s != null) {
    s.setName(studentNameTB.Text);
    s.setGender(genderTB.Text);
    s.setBirthDate(birthdatePicker.Value);
   }
   studentNameTB.Text = studentListBox.SelectedItem.ToString();
   genderTB.Text = studentListBox.SelectedItem.ToString();
  }

2 个答案:

答案 0 :(得分:0)

您可以通过从列表中抓取所选项目并将其强制转换回其对象类型来减少大量代码。例如,在列表框的单击事件中,获取所选对象并立即将其强制转换为适当的类型:

Student selectedStudent = (Student)listBox.SelectedItem;

这里有一个更完整的例子:

private void FrmMain_Load(object sender, EventArgs e)
{
    //you would fill from your file... this is just an example
    List<Student> students = new List<Student>();

    students.Add(new Student() { FirstName = "Joe", Gender = "Male" });
    students.Add(new Student() { FirstName = "Karen", Gender = "Female" });

    listBox.DataSource = students;
    listBox.DisplayMember = "FirstName";
}

public class Student
{
    public string FirstName { get; set; }
    public string Gender { get; set; }
    public string DisplayString { get { return string.Format("Name of student: {0}\r\nGender: ({1})", FirstName, Gender); } }
}

private void listBox_SelectedIndexChanged(object sender, EventArgs e)
{
    Student selectedStudent = (Student)listBox.SelectedItem;
    MessageBox.Show(selectedStudent.DisplayString);
}

答案 1 :(得分:0)

问题在于你最后两行代码:

studentNameTB.Text = studentListBox.SelectedItem.ToString();
genderTB.Text = studentListBox.SelectedItem.ToString();

他们都将相同的文本分配给学生姓名和性别框。