C# - 分离 class return 值,存储在 listBox 项中,从 listBox 项到单独的标签

C# - Seperate class return values, stored in listBoxItems, from listBoxItems to seperate labels

public class newStudent_class
        {
            public String firstName;
            public String secondName;
            public DateTime birthday;

            public override string ToString()
            {
                return firstName+ " " + secondName + ", " + birthday.ToString("dd.MMM.yyy");
            }
        }

class 创建了 newStudents(first/second 姓名和生日) 单击按钮会将这些值存储在 listBox

listBox1.Items.Add(myNewStudent);

问题出在这里: 我希望 listBox1.SelectedItem 由名字、姓氏和生日分隔 并将它们存储在 lblFirstName.Text = "..." lblSecondName.Text = "..." 和生日一样

您可以为列表框的 SelectedIndexChanged 添加一个事件处理程序。然后在您的事件处理程序中,您可以将所选项目转换为您的 class 类型并将这些值放入您的标签中。

void MyListBox_SelectedIndexChanged(object sender, EventArgs e)
{
    var newStudent = myListBox.SelectedItem as newStudent_class;
    if (newStudent != null)
    {
        lblFirstName.Text = newStudent.firstName;

        // etc...
    }
}