C# Using a list of objects to populate combobox and keeping object properties accessible

让人想犯罪 __ 提交于 2019-12-13 19:34:25

问题


I'm having some difficulty populating a combobox with the values inside a list. The list contains the following.

public List<Classroom> classes= new List<Classroom>();

CONTAINS:

public List<Students> Members{ get;}

public Classroom(string naam, string code, int maxPersonen)
{
    Name= name;
    Code = code;
    MaxPeople= maxpeople;
    Members= new List<Members>();
}

i'm trying to populate my combobox with List classes and show each of these classes as following (currently using this):

foreach(Classroom classrooom in repository.classes)
{
    cmbClass.Items.Add(classroom.Name + " (" + classroom.Code + ")");
}

I want to visually show them like this, but still be able to access every other property of the classroom that is selected (when using).

Hope this is clear enough to understand! Thanks in advance!


回答1:


You need to bind the list as a datasource to the combobox rather than adding one by one. And, add read only property DisplayName to classroom to return Name + " (" + Code + ")" to use it as a display value. You can add datasource, set display value and the selected item property will return the object.

    cmbClass.DataSource = classes;
    cmbClass.DisplayMember = classroom.DisplayName; 

Reference - ComboBox Class: https://msdn.microsoft.com/en-us/library/system.windows.forms.combobox%28v=vs.110%29.aspx



来源:https://stackoverflow.com/questions/34250770/c-sharp-using-a-list-of-objects-to-populate-combobox-and-keeping-object-properti

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!