如何在ListBox中显示属性

  • 本文关键字:显示 属性 ListBox c# listbox
  • 更新时间 :
  • 英文 :


在我的类Student中,我有一个属性studentName,我想在我的列表框的每一行上显示。

我的 ListBox绑定到 List<Students> studentList

如何在列表框中显示每个学生的名称?

例如

foreach(Student s in studentList){
    ListBox.DisplayOnNewLine(s.studentName);
} 

另外,您可以使用数据绑定如下:

ListBox.DisplayMember = "studentName";
ListBox.DataSource = studentList;

您的班级学生的覆盖tostring:

public override string ToString()
{
    return this.studentName;
}

listbox使用必须显示的类的ToString函数来显示元素。如果覆盖该功能,则可以定义自己想要显示的内容。在您的Students类中,您可以覆盖这样的功能:

public override string ToString()
{
    return studentName;
}

将DisplayMember设置为要显示的属性例如

listBox1.DisplayMember = "studentName";

这样,您不必覆盖toString((

最新更新